Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to always fill the first empty input field. Keeps filling the first field

Tags:

jquery

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/>
like image 317
Kevin Lindmark Avatar asked Dec 06 '25 02:12

Kevin Lindmark


2 Answers

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/>
like image 145
Rory O'Kane Avatar answered Dec 08 '25 16:12

Rory O'Kane


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.

like image 44
puelo Avatar answered Dec 08 '25 16:12

puelo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!