Blend jQuery events with existing onclick attribute of an object

I use jQuery, but I am dealing with markup created in JSF pages. Many elements have onclick attributes provided by JSF code (which is not my area).

Example:

<div onclick="[jsf js to submit form and go to next page]">submit</div>

I am trying to add some client side validation using jQuery. I need something like this pseudocode:

$('div').click(function(e){
  if(myValidation==true){
     // do nothing and let the JS in the onlick attribute do its thing
  } else {
     $error.show();
     // somehow stop the onclick attribute JS from firing
  }

})

Is there any best practice for this?

It seemed to me that when loading the page, grab the value of the onclick attribute, remove the onclick attribute from the object, then ... well, where am I getting lost. I could cache JS as text in a data attribute, but I'm not sure how to do this later.

+3
source share
5 answers

eval, onclick jQuery, . onclick

<div onclick="alert('hi');">submit</div>

-

$(document).ready(function() {
    var divClick = $('#theDiv').attr('onclick');
    $('#theDiv').removeAttr('onclick');
});

$('#theDiv').bind('click', function(e) {
    if (myValidation == true) {
        // do nothing and let the JS in the onclick attribute do its thing
        eval(divClick);
    } else {
        $error.show();
        // somehow stop the onclick attribute JS from firing
        e.preventDefault();
    }
});
+3

false :

e.stopPropagation()

e.preventDefault()

.

+3

:

var originalEvent = $('div').attr("onclick");
$('div').attr("onclick", false);

$('div').click(function(e) {
        if (false) {
            // do nothing and let the JS in the onlick attribute do its thing

            eval(originalEvent);
        }
        else {
            alert("error");
            // somehow stop the onclick attribute JS from firing
        }

    });

http://jsfiddle.net/j4jsU/

if (false) if (true), , , .

+1

e.stopProgation() e.preventDefault(), , onclick() , .

..

0

- :

div=document.getElementById('test');
oldClick=div.onclick;
bol=false;
div.onclick=function(){
    if(bol){
        oldClick();
    }
    else {
       alert('YOU SHALL NOT RUN INLINE JAVASCRIPT'); 
   }
}
0

All Articles