When I submit a web form I call two functions, like this:
<form action="myaction" name="myform" method="post" onsubmit="return submithandler(this) && validate(this)">
The javascript:
function submithandler (form) {
// a function that replaces some diacritical marks to the correct form
return true;
};
function validate(form) {
// huge validation code
};
Works fine in all browsers, except Firefox; this browser does the submithandler(this) part, but ignores the validate(this). If I make the form tag like this (below), it does the validation but ignores submithandler(this).
<form action="myaction" name="myform" method="post" onsubmit="return validate(this) && submithandler(this)">
Any ideas please?
EDIT:
The Firefox problem must be within this script? Maybe var form = event.target; ? Please see here: Change characters on form submit
// The script replaces all instances of a letter (or whatever) inside all text fields in the form.
function submithandler (form) {
var form = event.target;
var i, l;
for (i = 0, l = form.elements.length; i < l; i += 1) {
if (form.elements[i].type === 'text') {
form.elements[i].value = form.elements[i].value.replace(/Ş/g, 'Ș');
form.elements[i].value = form.elements[i].value.replace(/ş/g, 'ș');
form.elements[i].value = form.elements[i].value.replace(/Ţ/g, 'Ț');
form.elements[i].value = form.elements[i].value.replace(/ţ/g, 'ț');
}
}
return true;
};
call the validate function inside the submithandler function:
function submithandler (form) {
// a function that replaces some diacritical marks to the correct form
if(isValid(form)){
return true;
} else{
return false;
}
};
function isValid(form) {
// huge validation code
//validation code: must return true if valid
if(valid){
return true;
} else {
return false;
}
};
Related
Hollo All,
I am creating a form that exports data on submit to an ecommerce solution called Foxycart. I would like the form to only proceed onto foxycart when the date field is entered however it currently only displays the alert message then proceeds to the action on the form. Does anyone have advice on how to prevent the action on submit? please see code below:
<script>
function validateForm() {
var x = document.forms["delivery-date-info"]["Delivery_Date_is"].value;
if (x == null || x == "") {
alert("Date must be filled out");
return false;
}
}
</script>
<form name="delivery-date-info" action="https://austin-roman.foxycart.com/cart" method="post" accept-charset="utf-8" onsubmit="return validateForm()">
<div class="add-to-bag">
<label for="datepicker-example3"></label>
<input id="datepicker-example3" type="text" name="Delivery_Date_is">
<input type="submit" id="datepicker-example3" type="text" class="button-add">
</div>
</form>
Assuming you're using FoxyCart's default "sidecart" approach (as of v2.0), you'll need to use FoxyCart's own event system, described here. For your specific example, it might look like this:
var FC = FC || {};
FC.onLoad = function () {
FC.client.on('cart-submit', function(params, next) {
if (validateForm()) {
next();
}
});
};
function validateForm() {
var x = document.forms["delivery-date-info"]["Delivery_Date_is"].value;
if (x == null || x == "") {
alert("Date must be filled out");
return false;
} else {
return true;
}
}
Here's an alternate approach that'd be a bit more flexible, would allow more than one product form per page, and also shows a little more what's going on:
var FC = FC || {};
FC.onLoad = function () {
FC.client.on('cart-submit', function(params, next) {
$element = $(params.element);
if (
$element.attr('name') == 'delivery-date-info'
&& $element.find('[name="Delivery_Date_is"]').length > 0
&& !$element.find('[name="Delivery_Date_is"]').val()
) {
alert('Date must be filled out');
} else {
next();
}
});
};
I already checked How to prevent form from being submitted? but it did not help.
I have a register form with some input and a submit button
<script src="formValidation.js"></script>
<script src="md5.js"></script>
<script language="javascript">
function doSomething() {
str = document.registration.userpass.value;
str2 = document.registration.userpass2.value;
document.registration.response.value = MD5(str);
document.registration.response2.value = MD5(str2);
document.registration.userpass.value="";
document.registration.userpass2.value="";
formValidation();}
<form name="registration" action="/Arnito_test/Register" method="post" >
<input onClick="return doSomething();" type=submit>
formValidation.js:
function formValidation() {
...
if (registration.userpass.value == registration.username.value) {
alert("Error: Password must be different from Username!");
document.registration.userpass.focus();
return false;
}
...}
If I force this alert, it appears, but the form submits anyway.
the return false should block it, no?
doSomething() needs a return statement. The last line should be:
return formValidation();
Try -
Add "event" as a parameter that doSomething gets
Send it to formValidation
Add event.preventDefault();
function doSomething(event)
{
str = document.registration.userpass.value;
str2 = document.registration.userpass2.value;
document.registration.response.value = MD5(str);
document.registration.response2.value = MD5(str2);
document.registration.userpass.value="";
document.registration.userpass2.value="";
formValidation(event);
}
function formValidation(event) {
if (registration.userpass.value == registration.username.value) {
alert("Error: Password must be different from Username!");
document.registration.userpass.focus();
event.preventDefault();
return false;
}
}
I think you should use
<input onSubmit="return doSomething();" type=submit>
I have a function to swap data-attribute and action in a form:
$(function() {
function SwapAction() {
var dataAttr = $('.review-form').data();
$('.review-form')[0].action = dataAttr.action;
}
});
I want to do this upon submission of the form if the form passes validation checks. The validation JS looks like so:
var submitcount7303 = 0;
function checkWholeForm7303(theForm) {
var why = "";
if (theForm.FirstName) why += isEmpty(theForm.FirstName.value, "First Name");
if (theForm.LastName) why += isEmpty(theForm.LastName.value, "Last Name");
if (theForm.EmailAddress) why += checkEmail(theForm.EmailAddress.value);
if (why != "") {
alert(why);
return false;
}
if (submitcount7303 == 0) {
submitcount7303++;
SwapAction(); //Calling Function
theForm.submit();
return false;
} else {
alert("Form submission is in progress.");
return false;
}
}
The form doesn't submit and I receive an error:
Reference Error: SwapAction is not defined.
Here is the form HTML with the action:
<form action="" data-action="/FormProcessv2.aspx?WebFormID=89926&OID={module_oid}&OTYPE={module_otype}&EID={module_eid}&CID={module_cid}" enctype="multipart/form-data" onsubmit="return checkWholeForm7303(this)" method="post" name="catwebformform7303" class="review-form custom">
I assume I am overlooking something simple. If I remove SwapAction(); and remove the data-action and set the form back to default it works without a problem.
How do I fix the error and implement my script?
The function is not in scope, it's within the scope of the wrapping DOM ready function, so remove that :
function SwapAction() {
var dataAttr = $('.review-form').data();
$('.review-form')[0].action = dataAttr.action;
}
You define SwapAction() in the callback function of document ready, that's a different scope, so you can't access it in global scope.
SwapAction() is out of scope here.
If you want to use your first approach:
$(function() {
SwapAction = function {
var dataAttr = $('.review-form').data();
$('.review-form')[0].action = dataAttr.action;
}
});
And then you can call it as you are calling in your current code.
How do I make a script in javascript to output an error and prevent form submission with empty fields in the form? Say the form name is "form" and the input name is "name". I have been having some trouble with PHP not always handling the empty fields correctly, so I would like this as a backup. Any help is appreciated, thanks.
HTML Code :-
<form name='form'>
<input type="button" onclick="runMyFunction()" value="Submit form">
</form>
Javascript Code :-
function runMyFunction()
{
if (document.getElementsByName("name")[0].value == "")
{
alert("Please enter value");
}
else
{
var form= document.getElementsByName("form")[0];
form.submit();
}
}
Claudio's answer is great. Here's a plain js option for you. Just says to do nothing if field is empty - and to submit if not.
If you need to validate more than one, just add an && operator in the if statement and add the same syntax for OtherFieldName
function checkForm(form1)
{
if (form1.elements['FieldName'].value == "")
{
alert("You didn't fill out FieldName - please do so before submitting");
return false;
}
else
{
form1.submit();
return false;
}
}
This is untested code but it demonstrates my method.
It will check any text field in 'form' for empty values, and cancel the submit action if there are any.
Of course, you will still have to check for empty fields in PHP for security reasons, but this should reduce the overhead of querying your server with empty fields.
window.onload = function (event) {
var form = document.getElementsByName('form')[0];
form.addEventListener('submit', function (event) {
var inputs = form.getElementsByTagName('input'), input, i;
for (i = 0; i < inputs.length; i += 1) {
input = inputs[i];
if (input.type === 'text' && input.value.trim() === '') {
event.preventDefault();
alert('You have empty fields remaining.');
return false;
}
}
}, false);
};
Attach an event handler to the submit event, check if a value is set (DEMO).
var form = document.getElementById('test');
if (!form.addEventListener) {
form.attachEvent("onsubmit", checkForm); //IE8 and below
}
else {
form.addEventListener("submit", checkForm, false);
}
function checkForm(e) {
if(form.elements['name'].value == "") {
e.preventDefault();
alert("Invalid name!");
}
}
i have used the following code for javascript validation, that return true or false depending on the condition
javascript block
function fnval()
{
if(document.field.value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
Here is my HTML:
<Input type=submit name="sub" onClick="return fnval()">
Thus the js block checks if the field value is entered or not. If not it throws an alert message and return false, and hence the form does not get submitted.
But in case the value is not empty it returns a true, and still the form does not get submitted.
I have seen some queries asked by people where return false results in submission of the form. But this is exactly opposite.. and am not able to find a solution as of now.
Can anyone please help me on this?
Try getElementsByName:
function fnval()
{
if(document.getElementsByName('field')[0].value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
getElementsByName doesn't have IE support though. Perhaps:
function fnval()
{
if(findInput('field')[0].value == "")
{
alert("Invalid value");
return false;
}else{
return true;
}
}
function findInput(name) {
var elements = document.getElementsByTagName('input'),
length = elements.length,
i = 0,
results = [];
for(i; i<length; i++) {
if (elements[i].name === name) {
results.push(elements[i]);
}
}
return results;
}
You need to add the form name and the form value. Something like:
if ( document.formName.fieldName.value == "" )
For instance, with this kind of HTML:
<form method="post" onsubmit="">
Password: <input name="password" type="text" /><br />
</form>
The js:
if (document.form.password.value == "") {
//empty
}
i suggest using onsubmit in the form, <form ... onsubmit="return fnval()">,
try adding that and placing return false at the base of your function.
no matter what you do in js. but if you have filled action tag of form element element , the form will submit.
Syntax error:
type="submit"
not
type=submit