jQuery, submit() with multiple forms using .each() - javascript

First off, I realize this is not an optimal solution, but the actual production environment is a product of a drunken orgy involving Magento and a lot of cheap plugins, so don't judge me too harshly. I can't be held responsible for other peoples' messes.
I'm trying to submit multiple forms from one page using jQuery. It works fine in IE and FF. Page has four forms, which I loop through them in JS to see if their checkbox is checked and then submit them one by one, using .each() and .submit(). In Chrome, jQuery(this).submit() does not fire until after you have completely exited the function, and then it only actually submits the last form.
Uses jQuery 1.8.1. The working mockup is here
The code follows:
<!DOCTYPE html>
<html>
<head>
<title>asdfad</title>
<script type="text/javascript" src=http://code.jquery.com/jquery-1.8.1.min.js"></script>
</head>
<body class=" listraknewsletter-index-index">
<form id="form4" method="post" class="signup-form"
action="http://www.example.com/action1"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue1"/>
<label for="checkbox">newsletter 1</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox"
name="sos-checkbox" />
</form>
<form id="form2" method="post" class="signup-form"
action="http://www.example.com/action2"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue2"/>
<label for="checkbox">newsletter 2</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox"
name="sos-checkbox" />
</form>
<form id="form3" method="post" class="signup-form"
action="http://www.example.com/action3"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue3"/>
<label for="checkbox">newsletter 3</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox" name="sos-checkbox" />
</form>
<form id="form1" method="post" class="signup-form"
action="http://www.example.com/action4"
target="_blank">
<input type="hidden" name="crvs" value="hiddenValue4"/>
<label for="checkbox">newsletter 4</label>
<input name="checkbox" type="checkbox"
class="signup-checkbox" name="sos-checkbox" />
</form>
<!-- Area for entering in information -->
<form method="post" action="/">
<label for="email">email</label>
<input type="text" id = "nl_email" name="email"
size="40" maxlength="100" value = ""/>
<label for="name">name</label>
<input type="text" name="name" id = "nl_name" maxlength="50" size="40" value=""/>
<input type="button" value="Subscribe" onclick="processSignups();" />
<script type="text/javascript">
// requires jQuery
jQuery.noConflict();
function processSignups() {
// make sure you have a valid email and name
// make sure email is at least not null
// this is not a pretty regex for sure lol,
// but tis' RFC 2822 valid
var nl_email = jQuery('input#nl_email').val();
var re = new RegExp(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/);
if (re.test(nl_email) == false) {
alert('Please enter a valid email');
return false;
}
// name is not null
if (jQuery('input#nl_name').val() == '') {
alert('Please enter your name');
return false;
}
// make sure at least one checkbox is selected
var checkboxes = jQuery('input.signup-checkbox');
var atLeastOne = false;
jQuery(checkboxes).each(function() {
if (jQuery(this).is(':checked')) {
atLeastOne = true;
}
});
if (atLeastOne == false) {
alert('Please select at least one newsletter checkbox');
return false;
}
// select your forms by class
// var forms = jQuery('form.signup-form');
// for each form
var formIds = new Array();
jQuery('form.signup-form').each(function(index) {
// get the checkbox
var checkbox;
checkbox = jQuery(this).children('input.signup-checkbox');
// if it is checked
if (jQuery(checkbox).is(':checked')) {
// add a hidden field to the form to hold the email
jQuery(this).append('<input type="hidden" name="email" value="' + nl_email + '" />');
// and submit form
jQuery(this).submit();
}
});
// might as well clear the email and name inputs
jQuery('input#nl_name').val('');
jQuery('input#nl_email').val('');
// return false;
}
</script>
</form>
</body>
</html>

Chrome doesn't treat target="_blank" like the other browsers. Try _tab, or dynamically changing them $(this).attr('target', '_'+$(this).attr('id'));

Related

Use javascript with POST method

sorry for that, but I need your help on something :
I need to get my values in javascript, as it was filled in my form, and I have no clue how to do it, as whenever I tried to search, it was made for people with at least some understanding of javascript. I have none, but tried my best, the results of my efforts are here :
function validateForm() {
var x = form.('form').elements["sexe"];
if (x == null) {
alert("Un sexe doit être sélectionné");
return false;
}
}
I need to get it done by POST method, as get isn't allowed :
<form action="Monformulairedereferencement." method="post" id="sexe" name="form">
<div id="BlueBorder1">
sexe
<input type="radio" id="Homme" name="sexe" value="Homme" aria-checked="true">
<label for="Homme">Homme</label>
<input type="radio" id="Femme" name="sexe" value="Femme" aria-checked="true">
<label for="Femme">Femme</label>
<input type="radio" id="Autre" name="sexe" value="Autre" aria-checked="true">
<label for="Autre">Autre</label>
</div>
<div>
<label for="civilite">civilite</label>
<select name="civilite" id="civilite">
<option value="M.">M.</option>
<option value="Mme.">Mme.</option>
</select>
</div>
<div>
<label for="nom">nom</label>
<input type="text" id="nom" name="nom" minlength="2">
</div>
<div id="BlueBorder2">
<label for="email">email</label>
<input type="email" id="email">
</div>
<div>
<label for="telephone">telephone</label>
<input type="tel" id="telephone" name="telephone">
</div>
<div>
<label for="website">website</label>
<input type="url" name="website" id="website">
</div>
<div id="BlueBorder3">
<label for="datedenaissance">date de naissance</label>
<input type="date" id="datedenaissance" name="date de naissance">
</div>
<div>
hobbies
<input type="checkbox" id="Jeuxvideo" name="hobbies">
<label for="Jeuxvideo">Jeux video</label>
<input type="checkbox" id="Cinema" name="hobbies">
<label for="Cinema">Cinema</label>
<input type="checkbox" id="Lecture" name="hobbies">
<label for="Lecture">Lecture</label>
<input type="checkbox" id="Sport" name="hobbies">
<label for="Sport">Sport</label>
<input type="checkbox" id="Informatique" name="hobbies">
<label for="Informatique">Informatique</label>
</div>
<input id="token" name="token" type="hidden" value="my first website">
<div>
<label for="validation">validation</label>
<input type="submit" value="Envoyer le formulaire" id="validation">
If you have any clue of what isn't working or anything, then I'll gladly accept it. My only goal is to improve and I'm currently very bad.
Have a nice day and thanks for passing by :)
To get a value of a text input in JS, you need to get this input then get its value.
So for example: <input type="text" id="nom" name="nom" minlength="2">
to get this input value in JS, you have to follow 2 steps:
Assign the input element to variable -> let nom = document.getElementById('nom');
Get the value of this input element -> let nomValue = nom.value;
The previous approach can be applied to any text input (text, password, email, ...), textarea, & select menu
For checkboxes or radio buttons, you need to check if they are checked or not, for example: <input type="radio" id="Homme" name="sexe" value="Homme" > to check this, follow 2 steps:
Assign checkbox or radio button to a variable -> let Homme = document.getElementById('Homme');
Check if this checkbox or radio button is checked -> if (Homme.checked) {console.log('Checked')} else {console.log('Checked')}
For simple validation approach for your code, follow this snippet:
<!-- HTML Form -->
<form action="x.php" method="post" id="sexe" name="form">
<input type="text" id="nom" name="nom" minlength="2">
<input type="radio" id="Homme" name="sexe" value="Homme">
<input type="submit" value='Send' >
</form>
<!-- Validation Script -->
<script>
// Get Form Itself
let myForm = document.getElementById('sexe');
// Add Event To Form On Submit, Trigger The Validation Funcntion
myForm.addEventListener('submit', validateForm)
// Validate Form Function
function validateForm(e) {
// Get All Inputs In Your Form
let nom = document.getElementById('nom'); // Text Input
let Homme = document.getElementById('Homme'); // Radio Input
// Check Text Input Value If Not Empty
if(nom.value === '') {
// Prevent Form Submition
e.preventDefault();
// Alert Error Message
alert('Name Can Not Be Empty');
}
// Check If Radio Button Not Checked
else if (!Homme.checked) {
// Prevent Form Submition
e.preventDefault();
// Alert Error Message
alert('Radio Button Is Required');
}
// If The Previous Two Validation Steps Is Done And No Errors, The Form Will Be Sent
}
</script>
In my view, the easiest way to grab the value from the form is to use addEventListners with Submit event. It looks likes an element.addEventListner('submit',function);
var forms = document.getElementsByTagName('form'); //we have selected whole form
function formSubmitted(){
const emails = document.getElementsById('email');//select the email section
let emailValue = emails.value // it will give you the value of email after submitting
}
forms.addEventListner('submit',formSubmitted);//eventlistern which run after submiting the data in form

Why the onsubmit doesnt work and if I call the function in the console it runs?

I have this html:
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<script src="js/filename.js"></script>
</head>
<body>
<form id = "dp5" action="" method="POST" onsubmit="Write_Text()">
<h3>5- Do you know any browsers?</h3>
<input id = "No" type="radio" name="dp5N" value="false">
<label for = "No">No </label>
<input id = "yes" type="radio" name="dp5S" value="true">
<label for = "yes">Yes</label>
<label for = "text">6 - Which?</label>
<input id = "text" type="text" name="dp5text" value="">
</form>
<div id="next">
<input id="sub" type="submit" name="submit" value="Next">
</div>
</body>
</html>
And this javascript "filename":
function Write_Text() {
let x = document.forms["dp5"]["No"].value;
if (x === "false") {
document.getElementById("text").disabled=true;
document.getElementById("text").value="";
} else {
document.getElementById("text").disabled =false;
}
}
The text box should start disabled and only be able when the user choose "yes" option. The function isn't working at all.
Your submit button is outside the form. Put it inside the form and it will work.
<form id = "dp5" action="" method="POST" onsubmit="Write_Text(); return false">
<h3>5- Do you know any browsers?</h3>
<input id = "No" type="radio" name="dp5N" value="false">
<label for = "No">No </label>
<input id = "yes" type="radio" name="dp5S" value="true">
<label for = "yes">Yes</label>
<label for = "text">6 - Which?</label>
<input id = "text" type="text" name="dp5text" value="">
<div id="next">
<input id="sub" type="submit" name="submit" value="Next">
</div>
</form>
Once you fix the problem Sreekanth MK pointed out, you'll have a new problem:
Nothing is preventing the default action of the form submission, which is to send the form data to the action URL (in your case it will be the page's own URL) and replace the current page with whatever that URL returns.
You need to prevent the default action. The minimal way is:
<form id = "dp5" action="" method="POST" onsubmit="Write_Text(); return false">
or
<form id = "dp5" action="" method="POST" onsubmit="event.preventDefault(); Write_Text();">
...but I recommend using modern event handling instead by removing the onsubmit attribute and changing the JavaScript like this:
function Write_Text(event) {
event.preventDefault();
let x = document.forms["dp5"]["No"].value;
if (x === "false") {
document.getElementById("text").disabled=true;
document.getElementById("text").value="";
} else {
document.getElementById("text").disabled =false;
}
}
document.getElementById("dp5").addEventListener("submit", Write_Text);
Note that you need to move your script tag. Putting script in head is an anti-pattern. Scripts go at the end of the page, right before the closing </body> tag.
Side note: You're free to do anything you like in your own code, but FWIW, the overwhelming convention in JavaScript is that function names start with a lower case letter and use camelCase, other than constructors which used initially-capped CamelCase instead. So writeText rather than Write_Text.
First of all, the submit problem can be easily solved by moving the button in the form and preventing the default behavior.
Among the submit problem, I think your code could be significantly improved by also solving the following problem: you can select both of the radio inputs: wrap them into a field-set and use the same name for them; why? it's easier to get the selected answer and can be extended to multiple inputs.
Below you have a working example with what I said.
Cheers!
function Write_Text(event) {
event.preventDefault();
let x = document.querySelector('input[name="ans"]:checked').value
console.log(x);
if (x === "false") {
document.getElementById("text").disabled=true;
document.getElementById("text").value="";
} else {
document.getElementById("text").disabled =false;
}
}
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
</head>
<body>
<h3>5- Do you know any browsers?</h3>
<form id="dp5" action="" method="POST" onsubmit="return Write_Text(event)">
<fieldset>
<input id="No" type="radio" name="ans" value="false">
<label for="No">No </label>
<input id="yes" type="radio" name="ans" value="true">
<label for="yes">Yes</label>
</fieldset>
<label for="text">6 - Which?</label>
<input id="text" type="text" name="dp5text" disabled value="">
<div id="next">
<input id="sub" type="submit" name="submit" value="Next">
</div>
</form>
</body>
</html>
you need to use event object here to prevent Default because page get refreshed onSubmit and then submit form in your function Write_Text()
function Write_Text(event) {
//This will prevent Default Behaviour
event.preventDefault();
let x = document.forms["dp5"]["No"].value;
if (x === "false") {
document.getElementById("text").disabled=true;
document.getElementById("text").value="";
} else {
document.getElementById("text").disabled =false;
}
// then submit using JS
}

How to validate radio button and text field javascript

Below is my code
<!DOCTYPE html>
<head>
</head>
<body>
<form action="script.php" method="post" id="Form1">
<input name="radioGroup" type="radio" value="Radio1" id="Radio1id">
<input name="radioGroup" type="radio" value="Radio2" id="Radio2id">
<input name="radioGroup" type="radio" value="Radio3" id="Radio3id">
<br>
<br>
<input type="text" size="30" id="name" placeholder="Name*"><br>
<input type="text" size="30" id="email" placeholder="Email*"><br>
<input type="text" size="30" id="comments" placeholder="Comments (Optional)"><br><br>
<input type="submit">
</form>
</body>
</html>
Is there any way to validate radio button and text filed at same time. for an example if radio button is not checked or text field not used. should get a alert window.
Thanks,
Try something like that, or use JQuery because is easy to use for validation
if((document.getElementById('Radio1id').checked) && document.getElementById('name').value != "") {
//Action for checked radio button and text box without value
}else if(document.getElementById('Radio2id').checked) {
//Another Action . . .
}
if((document.getElementById('Radio1id').checked == false) && document.getElementById('name').value != "") {
//Action for NON checked radio button and text box without value
}
by using jQuery.
// valid syntax for jQuery
$("#Radio1id").is(":checked"); // for radio button
$("#email").val()===""; // for any input
use jQuery Validator , gives you more feature and choices down the road with any project. Plus, you can ask questions on GitHub.

Validating messages before submit

I'm making a html5 application which require all fields to be filled in before the submit button can be clicked.
What I want to do now is give an alert if a textbox is not filled in, the problem is that my submit button is disabled until all fields are filled in, so I can't really add an alert to that button.
Any idea's on how to solve this?
I want it so that after filling in the final textbox the submit button becomes available without first having to click on it.
Note that the 'required' does not work.
I have the following code:
HTML:
<form id="winForm">
<p>
<input type="text" id="name" name="name" required />
</p>
<p>
<input type="text" id="vorname" name="vorname" required />
</p>
<p>
<input type="text" id="email1" name="email1" required />
<label id="atteken" >#</label>
<input type="text" id="email2" name="email2 " required />
<textarea id="fullemail" name="fullemail"></textarea>
</p>
<p>
<input type="text" id="telefon" name="telefon" onclick="generateFullAdress()" required />
</p>
<p>
<input type="text" id="firma" name="firma" required />
</p>
<p>
<input type="submit" id="submitBtn" onclick="sendTheMail()" value=" ">
</button><div id="loading"><img src="images/loadingBar.gif" id="load"></img></div>
</p>
</form>
Jquery/JS
<script type="text/javascript">
function generateFullAdress() {
document.getElementById('fullemail').value =
document.getElementById('email1').value + '#' +
document.getElementById('email2').value;
}
</script>
<script>
var $input = $('input:text'),
$register = $('#submitBtn');
$register.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
if(trigger) {
$register.attr('disabled',true);
}else {
$register.removeAttr('disabled');
}
});
</script>
Help would greatly be appreciated.
Thanks!
If you have a form as such:
<form id="form">
...
</form>
You can use the following jQuery code to do something before the form is submitted:
$(function() {
$('#form').submit(function() {
// DO STUFF
return true; // return false to cancel form action
});
});
OR
perform the samething with the onsubmit event like
<form action="youraction" onsubmit="validatefunction" method="post">

Form alerts for multipe inputs

I have the following code, and need to get an alert that will specify which fields are empty or null, and return an alert for each empty or null field. I'm new to JavaScript and struggling a great deal with this. Can anyone give me some advice on this?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE></TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function checkForm(form){
var len = form.length;
//create for loop
for (var i=0; i<len; i++){
if (form.elements[i].type=="text" || form.elements[i].type==null){
if (form.fax number.value=="" || form.fax number.type==null){
alert("Please fill out the fax number field");
}
}
}
}
function emailTest(emailText){
var email = emailText.value;
var emailPattern = /^.+#.+\..{2,}$/;
if (!(emailPattern.test(email))) {
alert("Please enter a valid email address.");
document.myForm[1].focus();
}
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<H3>Assignment 2 Form</H3>
<HR>
<FORM NAME="myForm" METHOD="post"
ACTION="mailto:joeschmoe#blahblah.ca">
Name:<BR>
<INPUT TYPE="text" size="30" NAME="name"><br>
Email address:<BR>
<INPUT TYPE="text" size="30" NAME="email address" onBlur="emailTest(this);"><br>
Phone number:<BR>
<INPUT TYPE="text" size="30" NAME="phone number"><br>
Fax number:<BR>
<INPUT TYPE="text" size="30" NAME="fax number"><p>
<INPUT TYPE="submit" VALUE="Submit Data" onClick="return checkForm(this.form);">
<INPUT TYPE="reset" VALUE="Reset Form">
</FORM>
</BODY>
</HTML>
Ok...wow. I spent way too much time on this.
Your form should look like the following:
<FORM NAME="myForm" id="myForm">
<label for="name">Name:</label><br />
<INPUT TYPE="text" size="30" NAME="name" /><br />
<label for="email_address">Email address:</label><BR />
<INPUT TYPE="text" size="30" NAME="email_address" /><br />
<label for="phone_number">Phone number:</label><BR />
<INPUT TYPE="text" size="30" NAME="phone_number" /><br />
<label for="fax_number">Fax number:</label><BR />
<INPUT TYPE="text" size="30" NAME="fax_number" /><br />
<INPUT TYPE="button" VALUE="Submit Data" onClick="return checkForm()" />
<INPUT TYPE="reset" VALUE="Reset Form" />
</FORM>
Form Summary:
You should utilize labels for form elements
Never use spaces for the name attribute or any identifying attribute for that matter (name, class, id)
inputs should end with /> as should any tag without an end tag (<br /> too)
I pulled out the onBlur event and just added it as a piece of the overall validation process. No need to make it too complicated
I used a button input type instead of a submit input type. See why in the JavaScript
And then your JavaScript:
function checkForm() {
var valid = false; //Set a boolean variable that will be changed on each block
//of validation
if (document.myForm.fax_number.value === "") {
alert("Please fill out the fax number field");
}
if (document.myForm.email_address.value === "") {
alert("Email address is required");
} else {
valid = emailTest(document.myForm.email_address.value);
}
//all other checks within if statements
if (valid) {
document.myForm.action = "mailto:soandso#so.com";
document.myForm.submit();
}
}
function emailTest(emailText) {
var emailPattern = /^.+#.+\..{2,}$/;
var ret = false;
if (!(emailPattern.test(emailText))) {
alert("Please enter a valid email address.");
} else {
ret = true;
}
return ret;
}
Javascript Summary
In JavaScript interacting with HTML forms, forms are called as such: document.formName where formName is the string in the name="" attribute of the form tag or document.forms[i] where i is the numerical instance of the form on the page, i.e. the first form on the page is i = 0, thus it would be called as document.forms[0]
Check each input by name for a value with document.myForm.(elementName).value where elementName is the string from your <input>s name attribute.
Instead of using a submit, I used a regular button. When the "Submit Data" button is clicked in the form, it runs checkForm() which makes sure everything is valid
If everything is valid, it assigns an action to the form with document.myForm.action=youraction and then submits it via JavaScript with document.myForm.submit()
Notes
Don't use W3Schools to learn about anything ever.
Read more about forms here

Categories

Resources