Call Custom Function on Form Submit - javascript

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.

Related

Tried to get data from a form and append it to a global array, but for some reason the data isn't being added

I am trying to get data from a form and append it to a global array but for some reason, the data isn't being added to the array. The code should basically accept the input from the form and store it into the global array. I updated the HTML so you can see the entire syntax. The value should basically be taken from the form and placed into the global array using the "addnew" function.
function addnew()
{
//calculateAge();
//Accept values entered in form
const fname = document.getElementById('fname').value;
const mname = document.getElementById('mname').value;
const lname= document.getElementById('lname').value;
const dob= document.getElementById('dob').value;
const genderM = document.getElementsByName('male').checked;
const genderF = document.getElementsByName('female').checked;
const age = calculateAge.bYear;
const bodyType = document.getElementById('Body Type').value;
const occu= document.getElementById('occu').value;
const height= document.getElementById('height').value;
if (fname==null || fname=="")
{
alert();
}
if(mname==null || mname=="")
{
alert();
}
if (lname==null || lname=="")
{
alert();
}
if(dob==null || dob=="")
{
alert();
}
if (genderM.checked == false || genderF.checked == false){
alert();
}
if (age <=18 || age >=75)
{
alert();
}
if(height>=170 || height<=200)
{
alert();
}
if(bodyType==null || bodyType==""){
alert();
}
if(oocu==null || oocu=="")
{
alert();
}
//Append To array
records.push(fname);
records.push(mname);
records.push(lname);
records.push(dob);
records.push(genderM);
records.push(genderF);
records.push(age);
records.push(bodyType);
records.push(occu);
records.push(height);
for(i=0;i<records.length;i++)
{
console.log(records[i]);
}
//showAll();
//<h1 class="logo"><img src="New folder/logo.jpg" /></h1>
Information.addEventListener('submit', addnew);
}
</script>
```
first of all. name attribute has nothing to do with form element.
second. Information.addEventListener('submit', addnew); has no meaning because Information is not defined.
and to the core. when submiing a form, the page refreshes defaultly, so the addNew function is aborted like all the other variables. in order to prevent it you have to do as follows.
on submit button ad an id attribute:
<button id="submit" type="submit"> Submit </button>
then on top of your JS, get the button element and add an event listener to it:
let submit = document.getElementById('submit');
submit.addEventListener('click', addnew );
and here is the final step. on the addNew function, add an event argument. and on the begining of the function's code, fire the preventDefault method:
function addnew(event) {
event.preventDefault();
// the rest of the code here
}
by the way. you have a typo here. it should be occu.
if (oocu == null || oocu == "") {
alert();
}
good luck!

Javascript Regex Form validation returning error

I have been trying to validate my form email input with these line of codes.
function validate() {
var emailFirst = document.getElementById('email1');
var emailFirstRGex = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var emailFirstTest = emailFirstRGex.test(emailFirst);
if (emailFirstTest === false) {
alert('hello20');
}
}
My form
<form class="needs-validation" novalidate method="POST" action="nomination2.php" onsubmit="validate()">
I keep getting the hello20 response. Meanwhile i have tried this regex against emails on the console without error. How do I solve this?
emailFirstTest is declared inside your function, so checking for it outside the function means it is out of scope and doesn't exist.
Just define it above your function:
var emailFirstTest = '';
function validate() {
emailFirst = document.getElementById('email1');
var emailFirstRGex = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var emailFirstTest = emailFirstRGex.test(emailFirst);
}

Javascript form validation code looping

The following code loops when the page loads and I can't figure out why it is doing so. Is the issue with the onfocus?
alert("JS is working");
function validateFirstName() {
alert("validateFirstName was called");
var x = document.forms["info"]["fname"].value;
if (x == "") {
alert("First name must be filled out");
//return false;
}
}
function validateLastName()
{
alert("validateLastName was called");
var y = document.forms["info"]["lname"].value;
if (y == "") {
alert("Last name must be filled out");
//return false;
}
}
var fn = document.getElementById("fn");
var ln = document.getElementById("ln");
fn.onfocus = validateFirstName();
alert("in between");
ln.onfocus = validateLastName();
There were several issues with the approach you were taking to accomplish this, but the "looping" behavior you were experiencing is because you are using a combination of alert and onFocus. When you are focused on an input field and an alert is triggered, when you dismiss the alert, the browser will (by default) re-focus the element that previously had focus. So in your case, you would focus, get an alert, it would re-focus automatically, so it would re-trigger the alert, etc. Over and over.
A better way to do this is using the input event. That way, the user will not get prompted with an error message before they even have a chance to fill out the field. They will only be prompted if they clear out a value in a field, or if you call the validateRequiredField function sometime later in the code (on the form submission, for example).
I also changed around your validation function so you don't have to create a validation function for every single input on your form that does the exact same thing except spit out a slightly different message. You should also abstract the functionality that defines what to do on each error outside of the validation function - this is for testability and reusability purposes.
Let me know if you have any questions.
function validateRequiredField(fieldLabel, value) {
var errors = "";
if (value === "") {
//alert(fieldLabel + " must be filled out");
errors += fieldLabel + " must be filled out\n";
}
return errors;
}
var fn = document.getElementById("fn");
var ln = document.getElementById("ln");
fn.addEventListener("input", function (event) {
var val = event.target.value;
var errors = validateRequiredField("First Name", val);
if (errors !== "") {
alert(errors);
}
else {
// proceed
}
});
ln.addEventListener("input", function (event) {
var val = event.target.value;
var errors = validateRequiredField("Last Name", val);
if (errors !== "") {
alert(errors);
}
else {
// proceed
}
});
<form name="myForm">
<label>First Name: <input id="fn" /></label><br/><br/>
<label>Last Name: <input id="ln"/></label>
</form>
Not tested but you can try this
fn.addEventListener('focus', validateFirstName);
ln.addEventListener('focus', validateLastName);

Calling two functions in Firefox

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;
}
};

Return true - submitting an online form with Javascript

function FormSubmit(formid) {
this.initialize = function(formid) {
this.formid = formid;
$(formid).observe('submit', this.send);
}
this.send = function() {
alert('sending '+this.formid)
this.formid.onSubmit = true;
}
this.initialize(formid);
}
var form = new FormSubmit('donate_form');
<form method="post"
action="https://mysite.com/form_submit"
onsubmit="return false;" id="donate_form">
How can I make the above code, submit the form?
The event works, but the form doesn't submit.
Thanks
Rich
change
this.formid.onSubmit = true;
to
this.formid.submit();
Update
Whoops...forgot to double check the Javascript framework you were using. It looks like you're using Prototype. Please correct me if I'm wrong. In that case, instead of
this.formid.onSubmit = true;
you could try just
return true;
use document.forms[0].submit();
Also:
document.getElementById('donate_form').submit();

Categories