I have got a selector that selects multiple inputs with the given ID. I have got on input event that triggers when inputs changes for one of the inputs. I would like to check which input index position has triggered the input event. I guess they will be stacked or in my case they will be a list of Ids stored into array.
var getsIds $("#nameInput");
$(getsIds).on('input', function()){
//which event index from getsIds has triggered the input event
}
where #nameInput
is a list of inputs generated in the view and they all share the same id:
foreach(var items in Model){
<input type="text" id="nameInput" value="@items.name" >
}
bottom line is I would like to set validation on the input that triggered the event keeping them with the same Ids. How can I check which input triggered the event when they all share the same Ids ?
CodePudding user response:
IDs should be unique- only one element should have an ID on a page. When you use $('#nameInput')
to select them all, it'll only select the first since jQuery anticipates only one element with that ID.
You can add a class name instead:
<input type="text" id="nameInput1" class='nameInput' value="1" >
<input type="text" id="nameInput2" class='nameInput' value="2" >
<input type="text" id="nameInput3" class='nameInput' value="3" >
<input type="text" id="nameInput4" class='nameInput' value="4" >
<input type="text" id="nameInput5" class='nameInput' value="5" >
Then you can select them all, and use either the ID or the index within the parent (assuming they're all in the same parent element) to identify which was changed. this
in the listener will refer to the HTML element just changed and $(this)
will change that element into a jQuery object to manipulate.
var getsIds = $(".nameInput");
$(getsIds).on('input', function(){
console.log($(this).attr('id'));
console.log($(this).index());
});