Trying to fill a series of input fields so that always the first empty input is filled. Code seems to always fill the first input...any ideas?
jQuery(document).ready(function() {
for (i = 0; i < 4; i++) {
$('.field:empty:first').val(i);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="field" /><br/>
<input class="field" /><br/>
<input class="field" /><br/>
<input class="field" /><br/>
<input class="field" /><br/>
jQuery’s :empty selector does not select inputs that are empty, as you might think. Rather it means that the element has no child elements. This is the case of all input elements in your example. Then the :first selector selects the first element on each loop.
Intead, you can use .filter() to find field with an empty value followed by .first():
var emptyFields = $('.field').filter(function() { return $(this).val() === ""; });
emptyFields.first().val(i);
jQuery(document).ready(function() {
for (i = 0; i < 4; i++) {
var emptyFields = $('.field').filter(function() { return $(this).val() === ""; });
emptyFields.first().val(i);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="field" /><br/>
<input class="field" /><br/>
<input class="field" /><br/>
<input class="field" /><br/>
<input class="field" /><br/>
The empty selector (https://api.jquery.com/empty-selector/) does only select elements which have no child nodes (including text). This means that your first input field is always selected, regardless of it's value. This should work (if your numbered loop is not relevant):
$("input.field").each(function() {
if ($(this).val == '') {
$(this).val('filled');
return false;
}
})
A note: jQuery elements are ordered in document order, so that this should always fill the first empty input in the order they appear in the document.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With