Reputation: 11
How do I trigger a keyup event in this scenario
function check(form) {
form.addEventListener("keyup", event => {
if(event.target.value === "") {
form.querySelector(".error").innerText = "required"
} else {
form.querySelector(".error").innerText = ""
}
})
}
check(document.querySelector("#form1"))
<form id="form1">
<label>Name</label> <br />
<input type="text" />
<span class="error"> </span>
</form>
I want required to be placed without hard coding it. Currently it works only if i trigger a keyup event myself
Basically when I run this code required should be in the screen already since the input is empty
Upvotes: 0
Views: 51
Reputation: 1975
function check(form) {
// Get all .error elements
const errors = document.querySelectorAll('.error')
// Set inner text to 'required'
errors.forEach(error => error.innerText = 'required')
form.addEventListener("keyup", event => {
if(event.target.value === "") {
form.querySelector(".error").innerText = "required"
} else {
form.querySelector(".error").innerText = ""
}
})
}
check(document.querySelector("#form1"))
<form id="form1">
<label>Name</label> <br />
<input type="text" />
<span class="error"></span>
</form>
querySelectorAll(.error)
creates an array of every element with the class .error
then we create a for loop to loop through all elements with the class .error
and set the innerText
to required.
Upvotes: 1