Reputation: 2218
How do I get this ajax function to fire for each input field? Currently It only fires for the first field and no others without the page being refreshed.
html:
<input id='item_name_1' value='item_name' onclick='test("1", "item_name");'/>
<input id='item_value_2' value='item_value' onclick='test("2", "item_value");'/>
Jquery:
function test(id, field_name){
$('#'+field_name+'_'+id).keyup(function(){
$.ajax({
type: "POST",
url: "/admin/shop/update_harmonized_details",
data:{
id: id,
field_name: field_name,
field_value: $('#'+field_name+'_'+id).val()
},
success: function(resp){
if(resp.msg == 'Success'){
alert('Value Updated');
}
}
})
});
}
Upvotes: 0
Views: 77
Reputation: 5213
<input id='item_name_1' value='item_name' class="listenToMe" />
<input id='item_value_2' value='item_value' class="listenToMe" />
$('.listenToMe').keyup(function(){
var value = $(this).val();
var fieldID = $(this).attr('id').split('_');
var id = fieldID[2];
var name = fieldID[0] + '_' + fieldID[1];
console.log('Value: value');
console.log('ID:'+ id);
console.log('Name:'+name);
});
https://jsfiddle.net/vyeL9xu1/
If you wanted to avoid parsing the id
attribute you could just use data
attributes and reference the values with $(selector).data('attributename')
. So like you could add data-fieldname
to the input and reference it with $(this).data('fieldname')
.
Additionally it looks like you are updating data based on 'keyup'. AJAX calls are asynchronous and won't necessarily reach, process, or finish when you expect. You could potentially run into problems here. If someone typed in 'John' it would be sent to the server in that order, but o or h could get there last and then it wouldn't save it correctly. It would be best to either provide a save button or only fire a new event after the previous is complete, something like that.
Upvotes: 1