I am new to JavaScript. I have a form with an action and I need to fill the form inputs using JavaScript on submitting. I use an onsubmit function which executes as expected, but the form didn't hit the action in the action attribute and no data is sent to the server.
Can anybody help me find what is missing ?
JavaScript/jQuery:
$("#myForm").submit(function (e) {
e.preventDefault();
return fillFormValues();
})
function fillFormValues()
{
$.get( ...,function( data ) {
//fill my inputs values here
return true;
});
return false;
}
HTML:
<form action="..." method="post" target="output_frame" id="myForm">
<input name="first" id="first" type="hidden" value="">
...
<input type="submit" value="next">
</form>
what you can do is prevent the jQuery event default that would submit the form, do the ajax and once values are set trigger the native submit event that will bypass the jQuery submit listener
$("#myForm").submit(function(e) {
e.preventDefault();
fillFormValues(this);
});
function fillFormValues(form) {
$.get(..., function(data) {
//fill your inputs values here
form.submit(); //trigger native submit which is not caught by jQuery
});
}
Related
I'm working on an ASP.net web application.
I have a form with a submit button. The code for the submit button looks like <input type='submit' value='submit request' onclick='btnClick();'>.
I want to write something like the following:
function btnClick() {
if (!validData())
cancelFormSubmission();
}
How do I do this?
You are better off doing...
<form onsubmit="return isValidForm()" />
If isValidForm() returns false, then your form doesn't submit.
You should also probably move your event handler from inline.
document.getElementById('my-form').onsubmit = function() {
return isValidForm();
};
Change your input to this:
<input type='submit' value='submit request' onclick='return btnClick();'>
And return false in your function
function btnClick() {
if (!validData())
return false;
}
You need to change
onclick='btnClick();'
to
onclick='return btnClick();'
and
cancelFormSubmission();
to
return false;
That said, I'd try to avoid the intrinsic event attributes in favour of unobtrusive JS with a library (such as YUI or jQuery) that has a good event handling API and tie into the event that really matters (i.e. the form's submit event instead of the button's click event).
Sometimes onsubmit wouldn't work with asp.net.
I solved it with very easy way.
if we have such a form
<form method="post" name="setting-form" >
<input type="text" id="UserName" name="UserName" value=""
placeholder="user name" >
<input type="password" id="Password" name="password" value="" placeholder="password" >
<div id="remember" class="checkbox">
<label>remember me</label>
<asp:CheckBox ID="RememberMe" runat="server" />
</div>
<input type="submit" value="login" id="login-btn"/>
</form>
You can now catch get that event before the form postback and stop it from postback and do all the ajax you want using this jquery.
$(document).ready(function () {
$("#login-btn").click(function (event) {
event.preventDefault();
alert("do what ever you want");
});
});
you should change the type from submit to button:
<input type='button' value='submit request'>
instead of
<input type='submit' value='submit request'>
you then get the name of your button in javascript and associate whatever action you want to it
var btn = document.forms["frm_name"].elements["btn_name"];
btn.onclick = function(){...};
worked for me
hope it helps.
This is a very old thread but it is sure to be noticed. Hence the note that the solutions offered are no longer up to date and that modern Javascript is much better.
<script>
document.getElementById(id of the form).addEventListener(
"submit",
function(event)
{
if(validData() === false)
{
event.preventDefault();
}
},
false
);
The form receives an event handler that monitors the submit. If the there called function validData (not shown here) returns a FALSE, calling the method PreventDefault, which suppresses the submit of the form and the browser returns to the input. Otherwise the form will be sent as usual.
P.S. This also works with the attribute onsubmit. Then the anonymus function function(event){...} must in the attribute onsubmit of the form. This is not really modern and you can only work with one event handler for submit. But you don't have to create an extra javascript. In addition, it can be specified directly in the source code as an attribute of the form and there is no need to wait until the form is integrated in the DOM.
You need to return false;:
<input type='submit' value='submit request' onclick='return btnClick();' />
function btnClick() {
return validData();
}
With JQuery is even more simple: works in Asp.Net MVC and Asp.Core
<script>
$('#btnSubmit').on('click', function () {
if (ValidData) {
return true; //submit the form
}
else {
return false; //cancel the submit
}
});
</script>
Why not change the submit button to a regular button, and on the click event, submit your form if it passes your validation tests?
e.g
<input type='button' value='submit request' onclick='btnClick();'>
function btnClick() {
if (validData())
document.myform.submit();
}
You need onSubmit. Not onClick otherwise someone can just press enter and it will bypass your validation. As for canceling. you need to return false. Here's the code:
<form onSubmit="return btnClick()">
<input type='submit' value='submit request'>
function btnClick() {
if (!validData()) return false;
}
Edit onSubmit belongs in the form tag.
It's simple, just return false;
The below code goes within the onclick of the submit button using jquery..
if(conditionsNotmet)
{
return false;
}
use onclick='return btnClick();'
and
function btnClick() {
return validData();
}
function btnClick() {
return validData();
}
<input type='button' onclick='buttonClick()' />
<script>
function buttonClick(){
//Validate Here
document.getElementsByTagName('form')[0].submit();
}
</script>
I'm having trouble adding an event on a button that submits the form and after submission stopping the page redirect. I found other answers where I tried adding return false and preventDefault but neither are working.
Why is this not working?
function submitform() {
document.getElementById("form").submit( function () {
return false;
});
}
I added the click event to the button
<button id="button" onclick="submitform();">Submit Form</button
Here is an example that shows the javascript not working.
You are calling the function that is then listening for the form being submitted when there are no further events. Basically you are listening for an event that never comes.
There is no need to call the function on the submit in your supplied fiddle as the event is happening on the button.
I added a quick empty test for the email address just to show the process.
Amended Pen: https://codepen.io/anon/pen/dRRbyw
HTML
<button id="button" onclick="submitform();">Submit Form</button>
<br /><br />
<form id="form" method="post" action="https://submit.jotform.us/submit/71714528616156/">
Email
<input type="text" name="EMAIL" id="EMAIL" label="Email" value="">
JS
function submitform() {
if(document.getElementById("EMAIL").value == "") {
alert('nope');
return false;
} else {
alert('yep');
document.getElementById("form").submit();
}
}
Let me know if you need any more explanation.
you can use ajax to handle the form submission without redirecting the page. You will need to be using jquery for this solution:
$(function() {
$('form').submit(function() {
$.ajax({
type: 'POST',
url: 'submit.php',
data: { EMAIL: $(this).name.value }
});
return false;
});
})
incredibly similar question/answer here: Prevent redirect after form is submitted
How do I prevent this from submission when validation fails? I don't know what to put in the validateForm function... I have this form:
<form action="ChangePassword" method="POST">
<input type="submit" value="Change Password" onclick="validateForm();"/>
</form>
And the validateform function:
<script>
function validateForm() {
if(document.getElementById("passError").innerHTML !== "") {
alert("There are some errors.");
return false;
}
}
</script>
You need to return from your event handler function.
You are currently only returning from validateForm which is a function you call from your event handler function.
onclick="return validateForm();"
Good practise would be:
to perform the check when it is submitted rather then only when the submit button is clicked (i.e. use onsubmit on the form instead of onclick on the button).
to bind your event handlers with JavaScript instead of depending on globals and intrinsic event attributes
Maybe you have to stop the bubbling from your scope with e.preventDefault() instead of return false ?
function validateForm(event) {
if(document.getElementById("passError").innerHTML !== "") {
alert("There are some errors.");
event.preventDefault();
}
}
You have to do it in your form. Not in submit button. Like:
<form name="myForm" onsubmit="return validateForm();">
And also return true if your validation passes in your validate function.
I have a form with two submit buttons, Rails backend expects to receive one of the button names (action1 or action2) in the params hash. I want to show "are you sure?" message on one of the buttons. I have this code:
<form action="/models" id="myform" method="post">
<input name="action1" id="action1Button" type="submit" value="Make Action 1">
<input name="action2" type="submit" value="Make Action 2">
</form>
$('#action1Button').click(function() {
$('#popup').modal('show');
// cancel a submit
return false;
});
$('#popupSubmitButton').click(function() {
$('#myform').submit(); // I want this to trigger action1
});
$('#popupCancelButton').click(function(){
$('#popup).modal('hide');
});
The problem is that when form submits there is no name of the submitted button in the request. Is there a way to submit a form as though as submit button was actually clicked?
Trigger the event with trigger(), and in the event handler you can actually check if the event was triggered or not by checking event.isTrigger
$('#action1Button').on('click', function(e) {
if (!e.isTrigger) {
$('#popup').modal('show');
return false;
}
});
$('#popupSubmitButton').on('click', function() {
$('#action1Button').trigger('click');
});
$('#popupCancelButton').on('click', function () {
$('#popup').modal('hide ');
});
FIDDLE
I'm trying to stop a form from submitting using the submit eventlistener. My anonymous function runs but the form still submits, even with return false at the end of the function. There are no JS errors being thrown.
Am I making some stupid mistake?
<form id="highlight">
Row: <input type="text" name="rows" value="1" id="rows">
Column: <input type="text" name="cells" value="1" id="cells">
<input type="submit" name="Submit" value="Highlight" id="Submit">
</form>
<script>
var highlight_form = document.getElementById('highlight');
highlight_form.addEventListener('submit', function() {
alert('hi');
return false;
}, false);
</script>
I always call event.preventDefault() on event listeners that I want to cancel the event for, as well as return false. This always works for me.
<script>
var highlight_form = document.getElementById('highlight');
highlight_form.addEventListener('submit', function(event)
{
event.preventDefault();
alert('hi');
return false;
}, false);
</script>
To prevent form submission, I've always used the "onclick" event to call a javascript method which will do something and then submit from there. You can also setup the form as follows:
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
Once submitted, the validateForm() method can prevent submission if necessary:
function validateForm()
{
var x=document.forms["myForm"]["fname"].value
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
Well this is the way I would do it :
function validate (form)
{
// return false if some fields are not right
}
function setup_form_validation (form)
{
form.addEventListener (
'submit',
function (f) { // closure to pass the form to event handler
return function (evt) {
if (!validate (f)) evt.preventDefault();
// Return status doesn't work consistently across browsers,
// and since the default submit event will not be called in case
// of validation failure, what we return does not matter anyway.
// Better return true or nothing in case you want to chain other
// handlers to the submit event (why you would want do that is
// another question)
};
} (form),
false);
}
I would rather have a boolean holding the form validation status, though. Better update the status each time a field changes than do the check only when the user tries to submit the whole form.
And of course this will fail in IE8- and other older browsers. You would need yet another bloody event abstraction layer to make it work everywhere.