tags:

views:

30

answers:

3

Hi, I have the next code to work on ASP.Net controls.

I'm trying to add some javascript code to "onclick" event on a button when the result variable(res) is equals to "NO". The issue is that the first time it assigns the value to "onclick" it works fine, but when the removeAttr is executed and again the function is call and the res is equals to "NO" again it doesn't add the code on "onclick" event. So what's wrong on this? Thanks for your help. =)

Legend: - HLevel(Textbox) - PSave(LinkButton)

 $('#HLevel').blur(function () {
      // SOME CODE HERE BEFORE THE ISSUE CODE
      var res = $(msg).find("string").text();
      if (res == "NO") {
         $('#PSave').attr("onclick", "javascript:return confirm('some text');");
      } else {
        $('#PSave').removeAttr("onclick");
      }

  });
+1  A: 

You need to change the click event handler like so:

$('#HLevel').blur(function () {
     // SOME CODE HERE BEFORE THE ISSUE CODE
     var res = $(msg).find("string").text();
     if (res == "NO") {
        $('#PSave').click(function(){
            return confirm('some text');
        });
     } else {
        $('#PSave').unbind('click');
     }

 });
Pat
A: 

why not use jquery for it all instead of javascript onclick handlers. those are messy.

$('#PSave').click(function(){
    confirm('some text');

});

and instead of removeAttr use unbind.

$('#PSave').unbind();
Patricia
doh! Ninja'd by pat
Patricia
+1  A: 

Use the unbind() and click() methods:

if (res == "NO") {
    $('#PSave').click(function() {return confirm('some text');});
} else {
    $('#PSave').unbind("click");
}

If you use jQuery, try to make use of it as much as possible and don't mix styles.

Felix Kling
It works excellent!!! Thanks a lot Felix for your suggestion!!! From now on, I will use more jquery in order to avoid this kind of issue.
hanselp