kate_hudson kate_hudson - 2 years ago 79
Javascript Question

Defining when onclick is fired

I am having a little issue with something. I have a form, and I map the fields of the form within a system. The button of the form is automatically given an onclick event like this


It adds a vs variable which is needed. The problem is I need the form to have an input type button, not submit. I am using JQuery validation and I have this to trigger the form submission

$("#btn-default2").click(function() {

Now the issue with this, because of the onclick event, the validation quickly fires and then the onclick event does a redirect. I only want this redirect if the form is valid. Is there any way to stop the event onclick, and move it into my function where I check if the form is valid?


Answer Source

A procedural answer for your problem,

var btn = $("button.validate");
var x = btn.attr("onclick"); //get the onclick and store it in a variable.
btn.attr("onclick", ""); //remove the onclick attribute for that button
btn.click(function() {
    //Now do validations for your button.
    if ($("input[type='text']").val() == "10") { 
        eval(x); //If the form fields passed the validation
        //then trigger the redirect using eval


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download