John Doe 2 John Doe 2 - 5 months ago 21
jQuery Question

Jquery value integer with id through loop

I have a simple for loop:

for (var i = 0; i < 10; i++) {
$('#input' + i).on('blur', function() {
var values = $('#input' + i).val();
console.log(values);
});
}


I want to get the values of my #input, if I write something in my input I just get the message undefined in my console.

But Why if I run the following I get something correct ?

for (var i = 0; i < 10; i++) {
$('#input' + i).on('blur', function() {
var values = $('#input0').val();
console.log(values);
});
}


How do I put that values onto another id in that loop?

Answer

If you have really to use for loop try to separate the logic and you have to use event delegation .on() :

for(var i = 0; i< 6; i++) {
  $('body').on('blur', '#input'+i, getValue);
}

function getValue() {
  var values = $(this).val();
  console.log(values);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='input0' value='0' />
<input id='input1' value='1' />
<input id='input2' value='2' />
<input id='input3' value='3' />
<input id='input4' value='4' />
<input id='input5' value='5' />

But it will be better if you could avoid the loop and add general class for all your inputs or use start-with selector ^=:

$("boty").on('blur', '[id^='input']', function() {
    var values = $(this).val();
    console.log(values);
});

$('body').on('blur', '.input', function () {
  var values = $(this).val();
  console.log(values);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='input' id='input0' value='0' />
<input class='input' id='input1' value='1' />
<input class='input' id='input2' value='2' />
<input class='input' id='input3' value='3' />
<input class='input' id='input4' value='4' />
<input class='input' id='input5' value='5' />