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;">
Related
I'm creating a login form and in that if any input is wrong then i want to stay on the same page and notify the client to enter the correct input
I want to stay on this page http://localhost:8080/loginpage/ but after every click i'm redirected to http://localhost:8080/loginpage/?UserName=UserName&pword=&ConfirmPassword=&Email=Email&FirstName=First+Name&LastName=Last+Name&cars=male&Signup=Signup .
I have written a code for this but it does not seem to work.
if(t!==0)
{
var er="Email-id already exists";
window.location.reload(false);
document.getElementById("nemail").value=er;
document.getElementById("username").value=username;
document.getElementById("pword").value="";
document.getElementById("confpwd").value="";
document.getElementById("fname").value=fname;
document.getElementById("lname").value=lname;
document.getElementById("gender").value=gender;
}
I have tried to use several other methods like
window.location.replace('/loginpage/');
window.location.href="/loginpage/index.html";
But none of them works.
Please help!
There are two ways to prevent a form to submit.
Set form onsubmit="return false".
Register a submit event on a from. In the callback call event.preventDefault();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>1 way to prevent form to submit via onclick attribute</h2>
<form action="#submit-from-1-way" onsubmit="return validate(this)"><!--set onsubmit="return false"-->
<input name="value"/>
<button type="submit">Submit</button>
</form>
<h2>2 way to prevent form to submit via submit event</h2>
<form id="form" action="#submit-from-2-way"><!--set onsubmit="return false"-->
<input name="value"/>
<button type="submit">Submit</button>
</form>
<script>
console.log(location.href+'#'+location.hash+'?'+location.search);
function validate(form) {
return $(form).find('input').val();
}
$('#form').submit(function (e) {
if (!validate(this)) e.preventDefault();
});
</script>
You can use preventDefault() on the click event for a given html object. This will prevent the browser from taking the default action on a specific HTML object.
For example to prevent actoin on a link:
<body>
Click Me
<script>
function dontGo(event) {
event.preventDefault();
}
document.getElementById("clickMe").addEventListener("click",dontGo);
</script>
</body>
I'm using an asp.net webform page. I have some javascript that checks if some dynamically generated fields have values and then displays a message if not. The problem is that I haven't found a way to stop the form from being submitted when this check fails.
<form id="myform" name="myform" runat="server" onsubmit="finalCheck();">
I've tried button and input types:
<button type="submit">submit</button>
<input type="submit" value="submit"/>
The finalCheck() method always executes and does return false. But the form goes anyways.
Is there something else I need to do to prevent the form from being submitted?
write your html like this:
<form id="myform" name="myform" runat="server" onsubmit="finalCheck(event);">
then into your finalCheck(event) write this, on the first line for good practices:
event.preventDefault();
that will stop the submit and you can add more code after the preventDefault function to process the form data
The code in the event handler has to return the value from the function that it calls:
onsubmit="return finalCheck();"
The event handler function needs to return false. That function is onsubmit, not finalCheck.
onsubmit="return finalCheck();"
If you were using modern code, you could call preventDefault on the event object instead.
<script>
document.getElementById('myform').addEventListener('submit', finalCheck);
function finalCheck(event) {
var myForm = this;
// do stuff
event.preventDefault();
}
</script>
I need to select a form via native javascript (not jQuery) and prevent the form submission (preventDefault).
The trick is that the form does not have a name or id, and cannot be assigned one.
My HTML:
<div id="search">
<form method="get">
<input type="text" name="post"/>
<input type="submit" value="Post">
</form>
</div>
So far, I have tried to use document.forms[0] and document.getElementsByTagName("form")[0] to select the form, but the value returned is undefined.
Another possible solution is to overload the functionality of the submit button, but I did not have success with that either.
Using querySelector and an event listener, it's almost like jQuery
document.querySelector('#search form').addEventListener('submit', function(e) {
e.preventDefault();
});
note that the script has to come after the elements, or use a DOM ready handler, so the elements are available.
FIDDLE
Simple way is use onsubmit event handler
<script>
var submitHandler = function() {
// your code
return false;
}
</script>
<form method="get" onsubmit="return submitHandler()">....</form>
or more easy
<form onsubmit="return false;">
on form submit just return false.
e.g. <form onsubmit="return false">
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();
});
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.