views:

793

answers:

2
enter

scenario: I want to do an ajax call to update the image shown. Example: click to activate, click again to deactivate.

Now, image can change correctly when click for first time.

After that, if I click the img again, changes won't reflect anymore.

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>





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

    });         
}

here

+1  A: 

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.

cpharmston
Hi there, I found that this method only work in Firefox, not IE. Any workaround?
i need help
Did you do it the easy way or the right way?
cpharmston
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")')
i need help
+1  A: 

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.

cletus
I haven't think of this way. Thanks.
i need help