How to submit form after event.preventDefault();? - javascript

I have used javascript to add this when a particular page get loaded.
document.getElementById('commit').addEventListener("click", validateSubmit,
false);
this validateSubmit method have some code which will validate form data and
it will do this
function validateSubmit(){
//some code
window.addEventListener('submit', newsubmit, true);
HTMLFormElement.prototype._submit = HTMLFormElement.prototype.submit;
HTMLFormElement.prototype.submit = newsubmit;
}
function newsubmit(event) {
var target = event ? event.target : this;
event.preventDefault();
return false;
}
so for the first time while submitting form by clicking its coming in this method and it is preventing form values to submit and after fixing al those values when i am again trying to click on submit button then its not working,in console i am getting this error-
"Uncaught TypeError: Cannot call method 'preventDefault' of undefined"
Please help me...
Thanks in advance..

Try changing your function declaration from
function newsubmit(event) {
to
var newsubmit = function(event) {
the function has to be declared as a variable if you want to use it as a parameter of an event listener.

I don't think you need to go through such pains to prevent user from submitting incomplete form. Try this:
<form name="form1" id="form1" onsubmit="return validateForm()" ....>
<input type="text" id="txtName" />
</form>
function validateForm()
{
//CHECK IF FORM FIELDS CONTAIN VALID VALUES?
var formValid=....;//validation logic
return formValid;
}
Now if during validation you find any error you will set formValid variable to false otherwise if all input is correct set formValid to true. When form will getfalseas return value fromvalidateForm` function it will not submit.

Try this:
function validateSubmit(){
window.addEventListener('submit', newsubmit, true);
HTMLFormElement.prototype.submit = newsubmit;
HTMLFormElement.prototype._submit = HTMLFormElement.prototype.submit;
}
function newsubmit(event) {
var target = event ? event.target : this;
event.preventDefault();
return false;
}

Related

sessionStorage on form submit

I am creating a form and the onsubmit attribute has a form validation boolean method. At the end of the method, it does not matter whether or not none of the invalid inputs have returned false, the sessionStorage variable is to be updated to true so that upon loading the page again the variable will be rechecked. Why is the variable still false whether none of the inputs returned false or not? Keep in mind that the form action attribute leads to the same page (form page). This is how my validation looks like:
<form action="form.jsp" onsubmit="return validate()">
<input type="text" id="foo" />
<input type="submit">
</form>
var input = document.getElementById("foo"); // textbox
function validate()
{
if (input.value.trim() === "") {
return false;
}
sessionStorage.setItem("submitted","true");
}
Keep in mind that all form inputs exist and the sessionStorage variable is not updated even after the function doesn't return false.
Looking at your jsfiddle code, the reason is because you are checking its value like this:
if (sessionStorage.getItem("submitted") == true)
This is not accurate as the data stored there is a string... so to fix this you can do:
if (sessionStorage.getItem("submitted") == 'true')
You actually can't even check it like this:
if (sessionStorage.getItem("submitted"))
Because that will return true for any non-null value, even 'false'.
Try wrapping the sessionStorage call in a try/catch to see why it's failing.
function validate() {
var input = document.getElementById("foo"); // textbox
console.log('validate', input);
if (input.value.trim() === "") {
return false;
}
try {
sessionStorage.setItem("submitted", "true");
} catch (e) {
console.log(e);
return false;
}
// (for demostration purposes return false)
return false;
}
<form onsubmit="return validate()">
<input type="text" id="foo" />
<input type=submit>
</form>
Alternatively you can use the "Preserve log" checkbox in DevTools to retain the console errors.

prevent form submission (javascript)

I have a form with a text input:
<form name="form1">
<cfinput type="text" name="text1" id="text1" onChange="someFunc();">
</form>
I only want it to submit in certain cases. (I run some error-checking first)
<script>
function someFunc() {
if (1==2) {
document.form1.submit();
} else {
alert("Not submitting");
}
</script>
The problem is: even though the alert is triggering fine, somehow, the form is still submitting (There are no other submit statements aside from the one!).
Many thanks if anyone can shed some light on this . . .
There's a fundamental flaw with this approach. You are currently telling the form that when text1 changes, then call someFunc(). If true, use JavaScript to submit the form. If false, go on about your business. If you hit enter in the text input, the form still submits. If there is a submit button that gets clicked, the form still submits.
The basic way to approach this is like so:
<form name="form1" onsubmit="return someFunc()">
<input type="text" name="text1" id="text1">
</form>
When the from is submitted, call someFunc(). This function must return either true or false. If it returns true, the form submits. If false, the form does nothing.
Now your JavaScript needs a slight alteration:
<script>
function someFunc() {
if (1==2) {
return true;
} else {
alert("Not submitting");
return false;
}
}
</script>
You can still have other functions called when a field is changed, but they still won't manage the form's final submission. In fact, someFunc() could call the other functions to do a final check before returning true or false to the onsubmit event.
EDIT: Documentation on implicit form submission.
EDIT 2:
This code:
$(document).ready(function(){
$("#text1").on('change', function(event){
event.preventDefault();
});
});
is stopping the default processing for the change event associated with that element. If you want to affect the submit event, then you'd do this:
$(document).ready(function(){
$("#form1").submit(function(event){
event.preventDefault();
});
});
Which would allow you to do something like this:
$(document).ready(function(){
$("#form1").submit(function(event){
if ( $('#text1').val() !== "foo" ) {
alert("Error");
event.preventDefault();
}
});
});
var form = document.getElementById("Your Form ID");
form.addEventListener("submit", function (e) {
if ("Your Desired Conditions.") {
e.preventDefault();
}
});
use the following code it will work perfectly fine
<form onsubmit="return false;" >

Prevent action attribute from running php script with javascript [duplicate]

This question already has answers here:
prevent form from POSTing until javascript code is satisfied
(4 answers)
Closed 9 years ago.
Is there a way that I can use javascript to prevent a form from runing a php script. For example something like this:
<form action="somePage.php" method="POST>
<input type= "text" class= "field" name = "blah">
<input type="submit" value="Send" >
</form>
I know how to validate what's in that text box using javascript, but I want to prevent the somePage.php to run if the text box is empty. I haven't really tried anything cause I just don't know how to do it.
Hope you guys understand my problem.
Thanks
You can attach function to submit event of the form:
document.getElementById('form-id').addEventListener("submit", function(e){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null){
e.preventDefault();
alert('Pls fill the required fields.');
return;
}
return true;
});
OR
Below solution uses inline js:
If you want to run your js function before submitting the form to php script, you can use onsubmit attribute of the form,
<form id="form-id" action="somePage.php" method="POST" onsubmit="return formSubmit();">
<input type= "text" class= "field" id="field1" name = "blah">
<input type="submit" value="Send" >
</form>
In formSubmit function you can check the value of the input, if its empty or not, and if empty, then you can just return false;
var formSubmit = function(){
var field1 = getElementById('field1').value;
if(field1=='' || field1 == null)
return false;
else
return true;
}
You simply need to return false for your submit event by grabbing the form (I used querySelector because you have no IDs or classes), and adding a submit listening event to return false.
var x = document.querySelector("[method='POST']");
x.addEventListener("submit",function() {
return false;
});
Use this code to prevent form from submitting:
var first_form = document.getElementsByTagName('form')[0];
first_form.addEventListener('submit', function (e) {
e.preventDefault(); //This actually prevent browser default behaviour
alert('Don\'t submit');
//Do your stuff here
}, false);
Better read docs
you could in your somePage.php have this be a clause somewhere new the beggin:
if(empty($_POST['blah'])){
die();
}
or the inverse of
if(!empty($_POST['blah'])){
//do what this php is supposed to
}
else{
//display error
}
this will prevent your php from running if that field is not filled out.
Personally I return them to the same page setting some error on the page.

Displaying an image after pressing submit html

I have the following code to display an image after i press submit
<img id="image1" src="images/Coverflow1.jpg" style="display:none;"/>
<input type="submit" name="submit" value="submit" onclick="$('#image1').show()"/>
Name is retrieved by
var y=document.forms["myForm"]["fname"].value;
Where fname is
<h4>Name: <input type="text" name="fname" size="61" /></h4>
Only problem is this is using Jquery, so I can't seem to pass it through any of my other
validations like checking if the name field is null.
if (name==null || name=="")
{
alert("First name must be filled out");
return false;
}
Is there a Javascript equivalent to this that I can stick in my else statement so it will only show it if the form actually submits properly passing the validation checks beforehand?
Thanks
do all that in jquery.
if (name==null || name=="")
{
alert("First name must be filled out");
return false;
}
else
{
$('#image1').show()
}
You should be using the .submit() event handler of jQuery instead of attaching an onclick property to the submit button. The onclick property will not fire its function in the event that a user submits the form via the enter key; however, the .submit() method will capture it as well.
$("form[name=myForm]").submit(function(e) {
//get value of name here.
var name = this.fname.value; //this refers to the form, because that is what is being submitted.
//Do validation.
if (name == null || name == "") {
//If failed, then prevent the form from submitting.
alert("First name must be filled out.");
e.preventDefault();
return;
}
//If validation passed, show image.
$("#image1").show();
});
First, remove the onclick attribute from the submit button:
<img id="image1" src="images/Coverflow1.jpg" style="display:none;"/>
<input type="submit" name="submit" value="submit" />
Since you're using jQuery, attaching handlers to click events in JavaScript is a snap (and it's also a good practice).
I almost always use the following pattern for form validation (and on the submit of the form, rather than the click of the submit button because there are other ways to submit forms than clicking the button).
$(document).ready(function () {
var formIsValid = function formIsValid () {
// your validation routines go here
// return a single boolean for pass/fail validations
var name =document.forms.myForm.fname.value;
return !!name; // will convert falsy values (like null and '') to false and truthy values (like 'fred') to true.
};
$('form').submit(function (e) {
var allGood = formIsValid();
if (!allGood) {
e.preventDefault();
}
$('#image1').toggle(allGood); // hide if validation failed, show if passed.
return allGood; // stops propagation and prevents form submission if false.
});
});

Jquery set an event function on a form

I have a form thats displayed in a modal box now I want to be able to use the same modal box for 2 different pages where they do slightly different things. Is there a way I can set an event or something for the forms submit button to set which javascript function it calls.
I want to do this from within javascript without changing my form code.
Whats the best way to do this?
Can I set a function to a variable and have it called by my button code?
ie:
var buttonFunction;
//Set the button function on load
function MyButtonFuntion() {
buttonFunction();
}
you could do it like this:
var buttonFunction;
if(someCondition){
buttonFunction = function(){
alert("some action");
};
}else{
buttonFunction = function(){
alert("other action");
};
}
function MyButtonFuntion() {
buttonFunction();
}
You may declare a variable with the function name to be called on submit. The following code is an example. Declaring the function to call in a variable functionToCall inside the form will always work here.
<script type="text/javascript">
function callMyFunction(formName) {
var formObj = eval("document." + formName);
if(formObj != null) {
var functionToCall = eval(formObj.functionToCall.value);
if(functionToCall) {
functionToCall();
}
}
}
</script>
<form method="post" name="form1">
<input type="hidden" name="functionToCall" value="form1Function"/>
<input type="button" onclick="callMyFunction('form1')"/>
</form>

Categories