hello,
I'm working on a greasemonkey script that has a form (that isn't really a form, but just a collection of inputs - otherwise I guess I would be using beforesubmit) which is submitted somehow (dunno how, hoping not to have to find out) on the click of a button.
What I want to do is do a validation on the "form" before it gets sent. I struggled for a while because I was adding a click listener to the button (making the validation happen after the info was sent), but I realised that using "mousedown" I get to sneak in, and do the validation. I then just programatically click the submit button and away it goes.
Which is great. Works fine on my machine, anyway. But I have two doubts. A validation error brings up a confirm. If you click OK, the form sends. If you click cancel it doesn't. But shouldn't there be a return false in there somewhere, even though you would be returning false from the mousedown which I guess is unrelated to the click?
And that's the second question: The way I understand it, the event order is mousedown, click, mouseup. So what happens to the click event? Does it die while the confirm box is showing?
Here's a very basic example which demonstrates this. It's in jQuery because the page uses jQuery and I have to attach listeners to the dynamically created button (which I have no control over) - I know I can do that in vanilla, but it's just easier this way. But anyway, this isn't a jQuery question - the jQuery works fine. What I'm asking is how the javascript works here. More than anything, why don't I need to be canceling the click event in some way?
Any thoughts much appreciated.
Code:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
<body>
<input type="button" id="start" value="show form"/>
<script type="text/javascript">
$(document).ready(function () {
// these bits get done by the page - I have no control at this point
$("#send").live("click", function () {
$('#theform').remove();
alert("form sent!");
});
$("#start").click(function () {
$('body').append('<div id="theform"><input type="checkbox" id="cb"/>Check me or you\'ll get an alert<br>' +
'<input type="button" id="send" value="send form"/></div>')
});
// this is where the greasemonkeying starts
$("#send").live("mousedown", function () {
if (!($("#cb").is(":checked"))) {
if (confirm("You didn't check the box! Sure you want to continue?")) {
$("#send").click();
}
}
});
});
</script>
</body>
</html>