1

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>

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I haven't think of this way. Thanks.
1

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.

2 Comments

Hi there, I found that this method only work in Firefox, not IE. Any workaround?
easy way. It works well in FF, but IE having no respond after the first click. $('#'+'img'+pk).attr("src", src).parent('a').attr('onClick','update("7","no")')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.