I'm trying to submit a form using an anchor tag. However, the validation function doesn't seem to get triggered. I've since replaced the anchor with a submit button and it now works. Still, I'm curious why the previous anchor link didn't work.
The code is
function validate() {
/* validation code here */
return status;
}
<form id="myForm" action="/response_page.php" onsubmit="return validate();" method="POST">
<!-- form elements here -->
Submit
</form>
With this code, clicking the link goes straight to *response_page.php*. But when replaced with a submit button
<input type="submit" value="submit" />
WITHOUT changing the validate function and form tag, the validate function is called correctly. What's wrong with the anchor?
Thanks
This is expected behavior.
From the MDN on the submit function :
The form's onsubmit event handler (for example, onsubmit="return
false;") will not be triggered when invoking this method from
Gecko-based applications. In general, it is not guaranteed to be
invoked by HTML user agents.
If you want to validate your code in your link, just call the validate function explicitely :
<a id=subbut href="#" class="submit_button">Submit</a>
...
document.getElementById('subbut').addEventListener('click', function(){
if (validate()) document.getElementById('myForm').submit();
});
Related
<form method="POST" onsubmit="return false;">
...
<input type="submit" name="button" value="Login" onclick="require('file.js').submitForm(this.form);">
...
</form>
How can i trigger onclick event of this INPUT element (so it can submit the form) in Internet Explorer 9 using javascript?
I tried:
document.getElementsByName("button")[0].click()
and
document.getElementsByName("button")[0].onclick()
but neither works.
(document.getElementsByName("button").length = 1)
you can use
document.getElementsByTagName("form").submit();
and for click event you can use this
element = document.getElementsByName("button")[0]
if (typeof element.onclick == "function") {
element.onclick.apply(element);
}
Looking beyond the surface of your question, I believe you're trying to trigger a form post AND handle the submission with some client-side logic.
The code you have prevents the form from being posted because of "return false;". When the button is clicked, it'll triggered the submit event, which is blocked. So how do you know that the button is triggered or not, knowing the results are the same?
For simpler coding logic, put the JavaScript call either in the form tag or the button but not both. My advice is to leave the button be. type="submit" means it will submit the form. The the form itself has a JavaScript function that decides whether to post or not.
<form method="POST" onsubmit="return prepost();">
...
<input type="submit" value="Submit">
</form>
<script>
function prepost(){
// if the form needs to be stopped
return false;
// if the form needs to be posted
return true;
}
</script>
Answer: The form didn't submit if I left some fields blank. When i put correct values in right fields it submitted correctly using above click() method. Thank you all for answers.
Following is my code in which i am trying to accomplish, when user clicks on the submit button then my javascript function sets all the value to null in the textfields of the form whose id='contact_form' without loading the page . Kindly let me know how can i modify the following code to accomplish the functionality i've been trying to do.
Thanks!!
<script type='text/javascript'>
$(document).ready(function(){
$('#love').click(function(e) {
document.contact_form.name.value = '';
alert('aloha!!');
//stop the form from being submitted (not working fine)
e.preventDefault();
}
}
</script>
<form name='abc' action='' id='abc' >
<input type="submit" id='love' />
</form>
I have also tried the following function it worked fine but its not preventing from the page load
<script type='text/javascript'>
function js(){
document.contact_form.name.value = '';
//stop the form from being submitted (NOT WORKING!!)
preventDefault();
}
}
</script>
If you try onsubmit="return false;" in the form tag your form will not be submitted. Unfortunately it will NEVER be submit. Unless you are not planning to submit it via AJAX you have to modify your onsubmit event like this:
<form onsubmit="return callFunction()">
function callFunction() {
if(condition)
return true;
else
return false;
}
$("#abc").submit( function() {
// do everything you want.
return false; //will prevent the reload.
});
To have a function execute when the form submits you have to do something like this;
<form onsubmit="return validate();">
your form here
</form>
Then you can have your check in a function called 'validate()' (or whatever you want to call it)
Make sure the validate() function returns true is the form is allowed to submit, or returns false if the page is not allowed to submit.
Also put id's and names on your input elements, that way you can access them much easier.
Assuming you have an HTML like this :
<form>
<input type="text" id="text" />
<input type="submit" id='submit' value="clear above field without reloading" />
</form>
And you want the text field value to clear when a user submits without reloading using jQuery, then following script will be your remedy :
$(function(){
$('#submit').click(function(){
$('#text').value('');
})
});
A form can be submitted in many ways, not only by clicking on a submit buttons. You should really watch for submit events, and cancel them with preventDefault (instead of click events that might trigger the submit). See #user1359163's answer.
But you problem seem to be document.contact_form.name.value. There is no property contact_form on the document object, so this will raise an error. The preventDefault is not executed, your form gets submitted and you never see the error. Set your debugger to "Stop on errors"!
You might want something like document.forms["contact"], but I don't know your HTML. An id selector for the input element would be the better choice.
I want to prevent a form from being submitted using jQuery and instead run a function when the user wants to submit.
Here's my forms markup:
<form action="" method="post" id="msg-form">
<p><textarea name="msg"></textarea><input type="submit" value="Send"></p>
</form>
And my Javascript code:
$('#msg-form').submit(function() {
return false;
}
However, when I press the submit button, the form still gets sent and the page refreshes. How can I properly prevent the form from submitting?
It seems the event handler is not even executed, thus I assume the form could not have been found. Try enclosing your code within handler executed when the DOM is ready. In jQuery it can be simply done like that:
$(function(){
$('#msg-form').submit(function(event) {
event.preventDefault();
// code executed when user tries to submit the form
});
});
Also, as you can see above, you can prevent default behaviour of the form when it is being submitted.
The submit event is not actually being bound to the form element. You may have forgotten to bind it after the DOM was loaded!
Put the event binding inside of $(document).ready(function() { or load the script at the bottom of the page (after all of the elements have loaded).
$('#msg-form').submit(function(e){
e.preventDefault();
});
You could not give the users a real submit button and only submit the form using JS after validation:
HTML
<form action="" method="post" id="msg-form">
<p><textarea name="msg"></textarea><input id="submit" type="button" value="Send"></p>
</form>
JS
$('#submit').on('click', function() {
// validate
$('#msg-form')[0].submit();
});
Try:
$("#msg-form").submit(function (e) {
e.preventDefault();
});
This works
<form action='' onsubmit="return false;">
As does this
<form action='' onsubmit="doSomeWork();return false;">
I have two forms and a button. Everything works fine in Firefox. I get a new window, with a Paypal payment, and in the window where everything happened i get the send_mail form submitted that will send an e-mail to the user. How can I make this work in Chrome? Why it's not working? I've tried anything (or so I think)!
So:
<form name="registerForm" id="registerForm" target="_blank" action="paypal_url" method="post" onsubmit="$('#send_mail').submit();">
...
</form>
<form name="send_mail" id="send_mail" action="" method="post">
...
</form>
<a onclick="$('#registerForm').submit()">Go to paypal and send confirmation mail</a>
Unless you have a really good reason to use a javascript-only submit, why set up the form to be unusable if there is a javascript error?
Use a standard form input of type submit, give it an id, alter the look or text of the submit via javascript as necessary, and create onclick & onsubmit events as a layer on top of that functionality and have them return false. Better fallbacks.
I'm not sure why you're trying to submit two forms at once, but how about this alternative (note that I haven't tested this code, but it should convey the idea):
<script type='text/javascript'>
$('#fallback-register-submit').hide(); // Hide the submit button.
$('#registration-link').show().click(function (){ // Show the link and attach the action.
$('#registerForm').submit();
return false; // Don't bother following the link anchor.
});
</script>
<form name="registerForm" id="registerForm" target="_blank" action="paypal_url" method="post""><!-- Single form that does all of the submitting. -->
...
...
<input type='submit' id='fallback-register-submit'>Register</input><!-- In the event of a javascript error for their browser, they can still buy your stuff! -->
<a id='registration-submit' style='display:none'>Go to paypal and send confirmation mail</a>
</form>
why not just bind both submits to your a?
onclick="$('#send_mail').submit(); $('#registerForm').submit();"
if you want the other form to submit AFTER the first one:
onclick="$('#send_mail').submit( function() {$('#registerForm').submit();}); "
assuming you're using jquery here
As far as i understand, you want to submit the form using a link?
Why not use "plain" javascript then? Without jQuery: document.getElementById(....).submit()
Or link the submit event to the link in a normal jQuery way:
$(document).ready(function() {
$(".yourLinkClass").click(function() { // or "#yourLinkId" for that matter
$("#registerForm").submit();
});
});
And you also could use the submit button ;)
I have a type ahead text field, and when the user hits "Enter" I want to make an ajax call and not submit the form at the same time. My html looks like this:
<input id="drug_name" class="drugs_field" type="text" size="30" onkeypress="handleKeyPress(event,this.form); return false;" name="drug[name]" autocomplete="off"/>
<div id="drug_name_auto_complete" class="auto_complete" style="display: none;"/>
<script type="text/javascript">
//<![CDATA[
var drug_name_auto_completer = new Ajax.Autocompleter('drug_name', 'drug_name_auto_complete', '/sfc/pharmacy/auto_complete_for_drug_name', {})
//]]>
</script>
You should add an event handler to the form itself which calls a function to decide what to do.
<form onsubmit="return someFunction();">
And then make sure that your someFunction() returns false on success. If it returns true the form will submit normally (which is what you are trying to prevent!). So you can do your AJAX call, see if it succeeded, and return false.
Doing it this way you can provide a fallback in case your AJAX call fails and submit the form normally by returning true from your function.
Trap the event and cancel it.
It's something like trap onSubmit(event) and event.ignoreDefault(). The event can tell you that it was triggered by a keystroke, and which.
You could use a regular button that submits the form on click instead of your submit button.
If you want the enter key to work in other fields, just handle it there and submit the form.
in the input element for the button do:
<input type='submit' value='submit' onclick='submiFunction(); return false;'>
or on the form itself
<form blabla onsubmit='someAjaxCall(); return false;'>
Which should stop the form from submitting.
the return false is the action that actually stops the form from submitting (it cancels the current event, which is sbumit)