jQuery keyup function works. But there is a problem here. When I give data/value in one field, errors in other fields are also hidden. But I want to show / hide only that field when I give value or data.
$('#trexright input').keyup(function() {
if ($(this).val().length != 0) {
$('.field_error').hide();
} else {
$('.field_error').show();
}
});
#trexright p,
.form_field input {
width: 100%;
}
#trexright span {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="trexright">
<p class="form-row">
<label for="first_name" class="">First Name</label>
<span class="woocommerce-input-wrapper">
<input type="text" class="first_name_class" name="first_name" id="first_name_id" placeholder="First name" value="">
</span>
<span class="field_error">This field is required.</span>
</p>
<p class="form-row">
<label for="last_name" class="">Last Name</label>
<span class="woocommerce-input-wrapper">
<input type="text" class="last_name_class" name="last_name" id="last_name_id" placeholder="Last name" value="">
</span>
<span class="field_error">This field is required.</span>
</p>
<p class="form-row">
<label for="location" class="">Location</label>
<span class="woocommerce-input-wrapper">
<input type="text" class="location_class" name="location" id="location_id" placeholder="Location" value="">
</span>
<span class="field_error">This field is required.</span>
</p>
</div>
2
Answers
Well you are hiding/showing all the
.field-error
elements.You need to make a ‘ connection ‘ between
$(this)
which is the changed input and it’s correspondingfield-error
With the current HTML structure you can use the next() method to select the
field-error
that comes after the inputEDIT: after OP changed HTML structure.
Now the field-error is not a sibling for input so you cannot use
next
. But instead select the parent of the input ( span ) and then use next to select the field-error.I also formatted a bit the code so it’s more concise.
NOTE. As a personal advice. Please start learning the jquery methods. And see how you can traverse the HTML structure in order to select the items you want. Another advice is to start learning plain javascript and avoid using jquery altogether especially for large projects.
Try this will be work fine.