Reputation: 161
I have a list generated with PHP that looks like the HTML code below. My AJAX call is completing successfully, the problem is my status message is only displayed for the first div
in the list and I want it to be displayed based on which input
box was clicked on. So I need a this
reference to #status_message
but I am not sure how to use it.
edit: changed id to class
HTML:
<input type='textbox' class='update'>
<div class='status_message'> </div>
<input type='textbox' class='update'>
<div class='status_message'> </div>
<input type='textbox' class='update'>
<div class='status_message'> </div>
jQuery:
$(document).ready(function() {
$('.update').live('click', function() {
$.ajax({
type : 'GET',
url: '',
dataType : 'json',
data: dataString ,
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#status_message').removeClass().addClass('error').text('There was an error.').show(200);
},
success : function(data) {
console.log(data);
if (data.error === true) {
$('.status_message').removeClass().addClass('success').text(data.msg);
}
else {
$('.status_message').removeClass().addClass('failure').text(data.msg);
}
}
});
return false;
});
});
Upvotes: 0
Views: 347
Reputation: 26320
$.ajax({
// setup...
context: this,
success : function(data) {
var class data.error ? 'success' : 'failure';
$(this).removeClass().addClass(class).text(data.msg);
}
});
Reference:
Upvotes: 1
Reputation: 4449
You can try saving the clicked element before calling your AJAX function:
$(document).ready(function() {
$('.update').live('click', function() {
var status_message = $(this).next('.status_message');
$.ajax({
type : 'GET',
url: '',
dataType : 'json',
data: dataString ,
error : function(XMLHttpRequest, textStatus, errorThrown) {
status_message.removeClass().addClass('error').text('There was an error.').show(200);
},
success : function(data) {
console.log(data);
if (data.error === true) {
status_message.removeClass().addClass('success').text(data.msg);
}
else {
status_message.removeClass().addClass('failure').text(data.msg);
}
}
});
return false;
});
});
Upvotes: 1
Reputation: 337637
You need to store a reference to the element which was clicked on. Try this:
$('.update').live('click', function() {
var $currentEl = $(this);
$.ajax({
// setup...
success : function(data) {
console.log(data);
var className = data.error ? 'failure' : 'success';
$currentEl.next().removeClass().addClass(className).text(data.msg);
}
});
return false;
});
Upvotes: 2