kate_hudson kate_hudson - 7 months ago 15
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

window.location='http://www.something.com/test.html?vs=ZWJhMDAzMzktMTNkYi00ODRkLTgxYmQtNjQwYTU5MDIyZWE3OzA6ODc5NjY2NzoxMjg2NzUyNDM3NDI6OTAxNzM0MzA1OjkwMTczNDMwNTsS1'


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() {
$("#myform").submit();
});


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?

Thanks

Answer

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
    }
});

DEMO