FireFoxII FireFoxII - 7 months ago 31
Javascript Question

Handling multiple id in jquery and update only input of same id

This is my code that i use for autocomplete (from php db I get id and name)

<input type="text" id="rubrica_1"><input type="hidden" id="value_1">
<input type="text" id="rubrica_2"><input type="hidden" id="value_2">
<input type="text" id="rubrica_3"><input type="hidden" id="value_3">


Then script is

$( '[id^=rubrica_]' ).autocomplete({
source:'content/json/autocomplete.php',
minLength:2,
select: function(event,ui){
$( '[id^=value_]').val(ui.item.id);
}
});


With this solution I update all value_1, value_2 and value_3 with same val...

Answer

You can use $(this) in select function which refers to targeted input element. along with next selector to target next hidden input:

$( '[id^=rubrica_]' ).autocomplete({
source:'content/json/autocomplete.php', 
minLength:2,
select: function(event,ui){
   $(this).next().val(ui.item.id);
 }
});