Thursday, December 06, 2012

Solution: Replacing jQuery attr onclick event not working in IE (Internet Explorer) Browser


Before IE 9, if you are replacing HTML element onclick attribute using jquery, the event won't fire. See below HTML and jQuery to replace the onclick attribute of anchor tag.

HTML:

   <div>  
     <a id="atest" style="cursor:pointer" onclick="showAlert1();"> Click to fire an event</a>  
   </div>  


jQuery:


  <script type="text/javascript">  
     $(function () {  
       $("#atest").attr("onclick", "showAlert1();showAlert2();");  
     });  
     function showAlert1()  
     {  
       alert("Alert 1");  
     }  
     function showAlert2() {  
       alert("Alert 2");  
     }  
   </script>  

Above jQuery, replacing the onclick attribute to show the two alert instead of single alert. This code won't work in IE 7/8 browser. To fix this, you can bind a custom click event using click method in jQuery.



  <script type="text/javascript">  
     $(function () {  
       $("#atest").click(function () { showAlert1(); showAlert2(); });  
     });  
     function showAlert1()  
     {  
       alert("Alert 1");  
     }  
     function showAlert2() {  
       alert("Alert 2");  
     }  
   </script>  

In some cases, you may have to replace the onclick attribute with your own custom attribute based on some logical situation. In that case,it's not easy to bind click event dynamically. Here is the magic to replace the entire anchor element with custom attribute anchor element.

  <script type="text/javascript">  
     $(function () {  
       var onc = $("#atest").attr("onclick");  
       var elemHTML = $("#atest").parent().html();  
       var finalElement = elemHTML.replace(onc, onc + "showAlert2();");  
       $("#atest").parent().html(finalElement);  
     });  
     function showAlert1()  
     {  
       alert("Alert 1");  
     }  
     function showAlert2() {  
       alert("Alert 2");  
     }  
   </script>  

1 comment:

lulur bali joss said...

salam kenal bos. lagi jalan jalan pagi nih