Reputation: 2386
scenario: I want to do an ajax call to update the image shown. Example: click to activate, click again to deactivate.
Now, the image can change correctly when clicking for the first time.
After that, if I click the img again, changes won't reflect anymore.
The reason, the onclick status still= yes How do I access the hyperlink element to rewrite the onclick part to onclick="update('7', 'no') at REFER HERE?
<a href="#" onclick="update('7','yes')" ><img id=img7 border=0 src="img/active.gif" ></a>
<script type="text/javascript">
function update(pk, enable) {
$.ajax({
url: "ajaxcall.asp",
type: "POST",
success: function (output) {
var status = output
if (status == 1) {
var src = ($('#' + 'img' + pk).attr("src") == "img/cross.gif") ? "img/tick.gif" : "img/cross.gif";
$('#' + 'img' + pk).attr("src", src);
//REFER HERE
}
},
complete: function () { },
data: 'pk=' + pk + '&enable=' + enable
});
}
</script>
Upvotes: 1
Views: 3419
Reputation: 625087
I'd do it this way. Firstly:
<a id="a7" href="#"><img border="0" src="img/active.gif"></a>
then
$(function() {
$("#a7").update("7");
});
function update(pk) {
var img = $("#img" + pk);
if (img.attr("src") == "img/cross.gif") {
enable = "no";
var src = "img/cross.gif";
} else {
enable = "yes";
var src = "img/tick.gif";
}
$.ajax({
url: "ajaxcall.asp",
type: "POST",
success: function(output) {
var status = output;
if (status == 1) {
img.attr("src", src);
}
},
complete: function(){ },
data: 'pk='+pk+'&enable='+enable
});
}
You don't need to pass in yes or no. You can derive it from the image src.
Upvotes: 1
Reputation:
The easy way out:
Replace this:
$('#'+'img'+pk).attr("src", src);
with this:
$('#'+'img'+pk).attr("src", src).parent('a').attr('onClick','update("7","no")').
The right way:
This Javascript should be unobtrusive. If it were, you could use jQuery's event binding system to run the event once, then unbind it.
Upvotes: 1