I want to use billingname[] and billingcity[] instead but I don't know how to write .value for these input. (Now I use ordinal number such as billingname1, billingname2 but I don't want ordinal number)
<script>
function FillBilling(f) {
if(f.billingtoo1.checked == true) {
f.billingname1.value = f.shippingname.value;
f.billingcity1.value = f.shippingcity.value;
}
if(f.billingtoo1.checked == false) {
f.billingname1.value = '';
f.billingcity1.value = '';
}
if(f.billingtoo2.checked == true) {
f.billingname2.value = f.shippingname.value;
f.billingcity2.value = f.shippingcity.value;
}
if(f.billingtoo2.checked == false) {
f.billingname2.value = '';
f.billingcity2.value = '';
}
}
</script>
<td bgcolor="eeeeee">
<b>Mailing Address</b>
<br><br>
<form id="add_field">
Name:
<input type="text" name="shippingname">
<br>
City:
<input type="text" name="shippingcity">
<br>
<input type="checkbox" onclick="FillBilling(this.form)" name="billingtoo1">
<em>Check this box if Billing Address and Mailing Address are the same.</em>
<p>
<b>Billing Address</b>
<br><br>
Name:
<input type="text" name="billingname1">
<br>
City:
<input type="text" name="billingcity1">
</p>
<input type="checkbox" onclick="FillBilling(this.form)" name="billingtoo2">
<em>Check this box if Billing Address and Mailing Address are the same.</em>
<p>
<b>Billing Address</b>
<br><br>
Name:
<input type="text" name="billingname2">
<br>
City:
<input type="text" name="billingcity2">
</p>
</form>
</td>
If you're not going to give each field a unique identificator (maybe a id property), you have to iterate over all of them in order to get the value for each one:
$('input[name="billingname[]"]').each(function() {
this.value = f.shippingname.value;
});
Not sure how the code actually works on your environment, but it should give you an idea.
Related
I have created a JavaScript function that checks a form during submitting the input and displays an error message if there's no input.
It works perfectly when none input is given. It displays all the error messages correctly.
The Problem: But if I leave just the first field blank i.e, the fullname; the if loop stops there and doesn't display the second or third error messages i.e, the streetaddr & quantity.
NOTE: This error happens only when one of streetaddr or quantity is not given with addition to the first field i.e, fullname.
What should I do to display the error messages correctly. According to the blank input regardless the input field comes first or second or third.
Also, I prefer to do this with just Vanilla JavaScript, no frameworks/libraries. I'm trying to learn!
Link(s): This is a challenge from Wikiversity
/* Checking form function */
function checkForm(){
window.alert("You clicked Submit!");
var fullNameCheck = document.getElementById("fullname");
var addressCheck = document.getElementById("streetaddr");
var quantityCheck = document.getElementById("quantity");
var is_valid = false;
/* If statements to check if text box is empty */
if (fullNameCheck.value=="" && addressCheck.value=="" && quantityCheck.value=="") {
document.getElementById("nameerrormsg").style.display="inline";
document.getElementById("addrerrormsg").style.display="inline";
document.getElementById("qtyerrormsg").style.display="inline";
is_valid = false;
} else if(fullNameCheck.value==""){
document.getElementById("nameerrormsg").style.display="inline";
document.getElementById("addrerrormsg").style.display="none";
document.getElementById("qtyerrormsg").style.display="none";
is_valid = false;
} else if (addressCheck.value==""){
document.getElementById("addrerrormsg").style.display="inline";
document.getElementById("nameerrormsg").style.display="none";
document.getElementById("qtyerrormsg").style.display="none";
is_valid = false;
} else if (quantityCheck.value==""){
document.getElementById("qtyerrormsg").style.display="inline";
document.getElementById("nameerrormsg").style.display="none";
document.getElementById("addrerrormsg").style.display="none";
is_valid = false;
} else {
document.getElementById("nameerrormsg").style.display="none";
document.getElementById("addrerrormsg").style.display="none";
document.getElementById("qtyerrormsg").style.display="none";
is_valid = true;
} return is_valid;
}
.errormsg{
color: red;
background-color: yellow;
display: none;
}
<form action="mailto:me#fakeemail.com" onsubmit="return checkForm();">
<fieldset>
<legend>Personal details</legend>
<p>
<label>
Full name:
<input type="text" name="fullname" id="fullname">
</label>
</p>
<p class="errormsg" id="nameerrormsg">Please enter your name above</p>
<p>
<label>
Street Address:
<input type="text" name="streetaddr" id="streetaddr">
</label>
</p>
<p class="errormsg" id="addrerrormsg">Please enter your street address</p>
<!-- Quantity input -->
<p>
<label>
Quantity:
<input type="text" name="quantity" id="quantity">
</label>
</p>
<p class="errormsg" id="qtyerrormsg">Please enter your quantity</p>
</fieldset>
<input type="submit" value="Submit it!">
</form>
I'd prefer to just make the fields required, no Javascript needed:
<form action="mailto:me#fakeemail.com" onsubmit="return checkForm();">
<fieldset>
<legend>Personal details</legend>
<p>
<label>
Full name:
<input type="text" name="fullname" id="fullname" required>
</label>
</p>
<p>
<label>
Street Address:
<input type="text" name="streetaddr" id="streetaddr" required>
</label>
</p>
<!-- Quantity input -->
<p>
<label>
Quantity:
<input type="text" name="quantity" id="quantity" required>
</label>
</p>
</fieldset>
<input type="submit" value="Submit it!">
</form>
Otherwise, you can first hide all the error messages. Iterate over all inputs in the form, and if invalid (missing), navigate to its ancestor p and then to the adjacent .errormsg and set its display.
It would also be a good idea to avoid inline handlers entirely, they have too many problems to be worth using. Attach listeners properly using addEventListener in Javascript instead.
document.querySelector('form').addEventListener('submit', () => {
for (const errormsg of document.querySelectorAll('.errormsg')) {
errormsg.style.display = 'none';
}
let valid = true;
for (const input of document.querySelectorAll('form input')) {
if (input.value) {
// valid
continue;
}
valid = false;
input.closest('p').nextElementSibling.style.display = 'inline';
}
return valid;
});
.errormsg{
color: red;
background-color: yellow;
display: none;
}
<form action="mailto:me#fakeemail.com">
<fieldset>
<legend>Personal details</legend>
<p>
<label>
Full name:
<input type="text" name="fullname" id="fullname">
</label>
</p>
<p class="errormsg" id="nameerrormsg">Please enter your name above</p>
<p>
<label>
Street Address:
<input type="text" name="streetaddr" id="streetaddr">
</label>
</p>
<p class="errormsg" id="addrerrormsg">Please enter your street address</p>
<!-- Quantity input -->
<p>
<label>
Quantity:
<input type="text" name="quantity" id="quantity">
</label>
</p>
<p class="errormsg" id="qtyerrormsg">Please enter your quantity</p>
</fieldset>
<input type="submit" value="Submit it!">
</form>
You could hide all the error text as initially. Then show the error text based on respected input failure
/* Checking form function */
function checkForm() {
window.alert("You clicked Submit!");
var fullNameCheck = document.getElementById("fullname");
var addressCheck = document.getElementById("streetaddr");
var quantityCheck = document.getElementById("quantity");
var is_valid = false;
/* If statements to check if text box is empty */
document.getElementById("nameerrormsg").style.display = "none";
document.getElementById("addrerrormsg").style.display = "none";
document.getElementById("qtyerrormsg").style.display = "none";
is_valid = true;
if (fullNameCheck.value == "") {
document.getElementById("nameerrormsg").style.display = "inline";
is_valid = false;
}
if (addressCheck.value == "") {
document.getElementById("addrerrormsg").style.display = "inline";
is_valid = false;
}
if (quantityCheck.value == "") {
document.getElementById("qtyerrormsg").style.display = "inline";
is_valid = false;
}
return is_valid;
}
.errormsg {
color: red;
background-color: yellow;
display: none;
}
<form action="mailto:me#fakeemail.com" onsubmit="return checkForm();">
<fieldset>
<legend>Personal details</legend>
<p>
<label>
Full name:
<input type="text" name="fullname" id="fullname">
</label>
</p>
<p class="errormsg" id="nameerrormsg">Please enter your name above</p>
<p>
<label>
Street Address:
<input type="text" name="streetaddr" id="streetaddr">
</label>
</p>
<p class="errormsg" id="addrerrormsg">Please enter your street address</p>
<!-- Quantity input -->
<p>
<label>
Quantity:
<input type="text" name="quantity" id="quantity">
</label>
</p>
<p class="errormsg" id="qtyerrormsg">Please enter your quantity</p>
</fieldset>
<input type="submit" value="Submit it!">
</form>
I need to add a message box and e-mail textbox and display everything in my form in the 'msgresults' tag.
I need to add a Message box and and e-mail text box. Then I need all information to be shown within the MsgResults tag. The radioboxes already are shown this way.
function validateForm(){
var name = document.getElementById("name").value;
var age = document.getElementById("age").value;
if (name == "" || name == null){
resultsMsg("We need your name please");
}else{
if(age == "" || name == null || isNaN(age)){
resultsMsg("Please enter a number for your age");
}else{
if(!getSkill()){
resultsMsg("Please select the type of problem you are having.");
}else{
resultsMsg("Type of Problem: " + getSkill());
}//end else
}// end function
}
}
function getSkill(){
var isChecked = false;
var theSelection;
var skills = document.getElementsByName('skillset');
for (var i=0; i < skills.length; i++){
if(skills[i].checked){
isChecked = true;
theSelection = skills[i].value;
break;
}
}
if(isChecked){
return theSelection;
}else{
return false;
} // end else
} // end function
function resultsMsg(s){
var resultsBox = document.getElementById("results");
resultsBox.innerHTML=s;
} // end function
<form name="form1" id="form1" action="" method="post">
<label>Full Name:
<input type="text" id="name" name="name">
</label>
<br> <!-- new line here -->
<label>Your Age:
<input type="text" id="age" name="age">
</label>
<br> <!-- new line here -->
<input type="radio" name="skillset" value="Technical Issues">Technical Issues</br>
<input type="radio" name="skillset" value="Recovery Issues">Recovery Issues</br>
<input type="radio" name="skillset" value="Hardware Issues">Hardware Issues</br>
<input type="radio" name="skillset" value="Software Issues">Software Issues</br>
<input type="radio" name="skillset" value="Software Crashes">Software Crashes</br>
<input type="radio" name="skillset" value="Hardware Malfunctions">Hardware Malfunctions</br>
<input type="radio" name="skillset" value="General Problems">General Problems</br>
<input type="button" value="Submit" onClick="validateForm();"> <input type="reset" value="Clear Form">
</form>
<div id="results"></div>
If I understand your goal correctly, you want to add the given name and age to the result-div, on top of the 'Type of Problem' that is already show. That can be easily achieved by adding the correct variables to the last else-loop in your validateForm function. Something among the following should probably work:
resultsMsg("Name: "+name+ "<br>Age: " +age+ "<br>Type of Problem: " + getSkill());
I have this assignment in my class where we are to make a simple form with three required fields (out of five). I am having problems with getting my code to work.
This is via my professor...with what he wants
{
On submitting the form, the browser should check that :
Values for the required fields have been entered
Use regular expressions to check that the form of the entered input is proper for the email, telephone, and website fields. The forms to check for are:
Email: [alphanumeric string including . and _ ]# [alphanumeric string including . and _ ]. [alpha string]
Telephone: Either (ddd)ddd-dddd or ddd-ddd-dddd etc
Website: www.[alphanumeric string including . _ -].[com or net etc]
If any error is found, the form should not be submitted and appropriate error messages should be generated.
}
All validation must be "client side" i.e. on the browser using Javascript (not on any server and no Jquery or any programming other than Javascript and the required HTML). Use of any authoring tools is strictly and expressly forbidden.
This what I have now. Please help. Below is the code. What am I doing wrong?
<script language = "JavaScript">
<!--
function validateForm(){
//This is to check that required fields are filled
var x = document.contact.Name.value;
var y = document.contact.Email.value;
var z = document.contact.Website.value;
var p = document.contact.Phone.value;
if(x==null || x ==""){
alert('Name must be filled out');
return false;
}
if (y ==null || y == ""){
alert('Email must be filled out');
return false;
}
if (z == null || z == ""){
alert('Website must be filled out');
return false;
}
if(!isEmail()){
alert('This is not a correct Email format');
}
if (!isTelephone()){
var errorText = document.createTextNode(
"This is not a correct Phone number format");
}
if(!isWeb()){
errorText = document.createTextNode(
"This is not the correct Website format");
}
}
function isTelephone(){
//This checks that the phone number is in the required format
return document.contact.Phone.value.match(
/^\(\d\d\d-d\d\d\-\d\d\d\d$/);
}
function isEmail(){
//This is for checking email format
return document.contact.Email.value.match(
/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/);
}
function isWeb(){
return document.contact.Website.value.match(
/^([wW]{3}\.)?[a-zA-Z0-9\-.]{3,}\[a-zA-Z]{2,}(\.[a-zA-Z]{2,})?$/);
}
-->
</script>
<body>
<form name="contact" action="" method="post" onSubmit = "return validateForm();">
Name: <input type="textbox" name="Name" value="" > <font color = red>*Required </font><br>
Company: <input type="textbox" name="Company" value="" > <font color = red>Optional </font><br>
Email: <input type="textbox" name="Email" value="" > <font color = red>*Required </font><br>
Telephone: <input type="textbox" name="Telephone" value="" > <font color = red>Optional </font><br>
Website: <input type="textbox" name="Website" value="" ><font color = red>*Required </font><br>
<input type="submit" value="Submit Contact Details">
<input type="reset" value="Clear"
ONCLICK="
alert('This will clear the form.');
Name.value=' '
Company.value=' '
Email.value=' '
Telephone.value=' '
Website.value=' '"><br>
</form>
</body>
</html>
Try this out:- https://jsfiddle.net/vduwxjmv/
This can be done without JavaScript also using required attribute at each html control for which value is mandatory. And for clear you can use input type as reset.
HTML:-
<form name="contact" action="" method="post">
Name: <input type="textbox" name="Name" value="" required> <font color = red>*Required </font><br>
Company: <input type="textbox" name="Company" value=""> <font color = red>Optional </font><br>
Email: <input type="textbox" name="Email" value="" required> <font color = red>*Required </font><br>
Telephone: <input type="textbox" name="Telephone" value="" > <font color = red>Optional </font><br>
Website: <input type="textbox" name="Website" value="" required><font color = red>*Required </font><br>
<input type="submit" value="Submit Contact Details">
<input type="reset" value="Clear" />
You can do a check by using the following JavaScript code
var result = $("#form")[0].checkValidity();
or you may change input button
<input type="submit" value="Submit Contact Details">
<!DOCTYPE html>
<html>
<body>
<form name="contact" method="post">
Name: <input type="text" class="form-control" name="Name" placeholder="Name" required="required" /> <font color = red>*Required </font><br>
Company: <input type="text" class="form-control" name="Company" placeholder="Company" /> <font color = red>Optional </font><br>
Email: <input type="email" class="form-control" name="Email" placeholder="Email" required="required" /> <font color = red>*Required </font><br>
Telephone: <input type="text" class="form-control" name="Telephone" placeholder="Telephone"/> <font color = red>Optional </font><br>
Website: <input type="text" class="form-control" name="Website" placeholder="Website" required="required" /><font color = red>*Required </font><br>
<input type="submit" value="Submit Contact Details">
<input type="reset" value="Clear"><br>
</form>
</body>
</html>
change the type from button to submit.
on giving the type as reset ,it will clear the contents.
on giving required="required", that field will be considered as a mandatory one.
<html>
<head>
<script language = "JavaScript">
function validateForm(thisVar){ alert('method Called From: ');alert(thisVar.value);alert(thisVar.name);
//This is to check that required fields are filled
var x = document.contact.Name.value;
var y = document.contact.Email.value;
var z = document.contact.Website.value;
var p = document.contact.Phone.value;
if(x==null || x ==""){
alert('Name must be filled out');
return false;
}
if (y ==null || y == ""){
alert('Email must be filled out');
return false;
}
if (z == null || z == ""){
alert('Website must be filled out');
return false;
}
if(!isEmail()){
alert('This is not a correct Email format');
}
if (!isTelephone()){
var errorText = document.createTextNode(
"This is not a correct Phone number format");
}
if(!isWeb()){
errorText = document.createTextNode(
"This is not the correct Website format");
}
}
function isTelephone(){
//This checks that the phone number is in the required format
return document.contact.Phone.value.match(
/^\(\d\d\d-d\d\d\-\d\d\d\d$/);
}
function isEmail(){
//This is for checking email format
return document.contact.Email.value.match(
/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/);
}
function isWeb(){
return document.contact.Website.value.match(
/^([wW]{3}\.)?[a-zA-Z0-9\-.]{3,}\[a-zA-Z]{2,}(\.[a-zA-Z]{2,})?$/);
}
</script>
</head>
<body>
<form name="contactForm" action="" method="post" onSubmit = "return validateForm(this);">
Name: <input type="textbox" name="Name" value="" > <font color = red>*Required </font><br>
Company: <input type="textbox" name="Company" value="" > <font color = red>Optional </font><br>
Email: <input type="textbox" name="Email" value="" > <font color = red>*Required </font><br>
Telephone: <input type="textbox" name="Telephone" value="" > <font color = red>Optional </font><br>
Website: <input type="textbox" name="Website" value="" ><font color = red>*Required </font><br>
<input type="submit" value="Submit Contact Details" onclick="validateForm(this);">
<input type="reset" value="Clear"
ONCLICK="
alert('This will clear the form.');
Name.value=' '
Company.value=' '
Email.value=' '
Telephone.value=' '
Website.value=' '"><br>
</form>
</body>
</html>
You can validate it by two ways ---
use Submit type button
call validationForm on button click
Like --
<input type="submit" value="Submit Contact Details">
or
<input type="button" onclick="return validationForm();" value="Submit Contact Details">
you can check method call from to times 1st from onclick 2nd from onsubmit
Dont forget to appreciate (vote up).
I am attempting to build a string of a user's "interests" that they indicate by checking off radio boxes. When I return the result, there is always an "undefined" prepended to the string of interests. I know that I can get rid of this issue by initializing var interest as an empty string, like so:
var interests ="";
But am unsure if this is the proper way to solve the issue. is there a more optimal data structure for this?
var controlIndex;
var element;
var interests;
var numberOfControls = document.form1.length;
for (controlIndex = 0; controlIndex < numberOfControls; controlIndex++)
{
element = document.form1[controlIndex];
if (element.type == "radio")
{
if (element.checked == true)
{
interests += document.form1[controlIndex].value+"\n";
console.log(interests);
document.getElementById("interests").innerHTML= interests
}
}
}
}
}
<form action="" name="form1">
<h1>Personal Details</h1>
Please enter the following details:
<br>
<p>
First Name:
<br />
<input type="text" name="txtName" onchange="txtName_onchange()"/>
</p>
<p>
Age:
<br />
<input type="text" name="txtAge" size="3" maxlength="3" onchange="textAge_onblur()" />
</p>
<p>
My interest is:
<p>Sports
<input type="radio" name="sports" value="sports"/>
</p>
<p>Politics
<input type="radio" name="politics" value="politics" />
</p>
<p>Magazines
<input type="radio" name="magazines" value="magazines">
</p>
<p>
<input type="button" value="Submit Registration" name="btnCheckForm" onclick="btnCheckForm_onclick()" >
<input type = "button" value = "Clear Details" name="btnClear" onclick="btnClear_onclick()">
</p>
</form>
</div>
I would turn your "interests" variable into an array.
var interests = [];
then I would just push into it, like so. When you want to print it out, just join it.
interests.push(document.form1[controlIndex].value);
console.log(interests.join(""));
But am unsure if this is the proper way to solve the issue ...
Yes, initialising the variable as a string is the proper way to resolve this issue.
Basically, whenever you initialise your variable like this:
var interests;
The variable type is implicitly set to undefined, so when you apply += onto it, JavaScript changes the type to string with a value of "undefined". Setting the initial value prevents that:
var interests = '';
I have tried to put same thing mentioned in above answers in code snippet for better understanding. In my opinion array suits here
function btnCheckForm_onclick (){
var controlIndex;
var element;
//Case with '' intitlization
var interests = '';
//Case with [] intitlization
var interests = [];
var numberOfControls = document.form1.length;
for (controlIndex = 1; controlIndex < numberOfControls; controlIndex++)
{
element = document.form1[controlIndex];
if (element.type == "radio")
{
if (element.checked == true)
{
// Case with []
//interests.push(document.form1[controlIndex].value);
//console.log(interests.join(" "));
//Case with ''
interests += document.form1[controlIndex].value+"\n";
console.log(interests);
}
}
}
document.getElementById("interests").innerHTML= interests
}
<form action="" name="form1">
<h1>Personal Details</h1>
Please enter the following details:
<br>
<p>
First Name:
<br />
<input type="text" name="txtName" onchange="txtName_onchange()"/>
</p>
<p>
Age:
<br />
<input type="text" name="txtAge" size="3" maxlength="3" onchange="textAge_onblur()" />
</p>
<p>
My interest is:
<p>Sports
<input type="radio" name="sports" value="sports"/>
</p>
<p>Politics
<input type="radio" name="politics" value="politics" />
</p>
<p>Magazines
<input type="radio" name="magazines" value="magazines">
</p>
<p>
<input type="button" value="Submit Registration" name="btnCheckForm" onclick="btnCheckForm_onclick()" >
<input type = "button" value = "Clear Details" name="btnClear" onclick="btnClear_onclick()">
</p>
<div id="interests"></div>
I want to make my Billing fields automatically match my Shipping fields. I can make it work with text values, but I can't automatically populate a RADIO BUTTON. I'm using this code: http://jsfiddle.net/aDNH7/ I would like to keep this in Javascript.
<script>
function FillBilling(f) {
if(f.billingtoo.checked == true) {
f.billingname.value = f.shippingname.value;
f.billingcity.value = f.shippingcity.value;
}
if(f.billingtoo.checked == false) {
f.billingname.value = '';
f.billingcity.value = '';
}
}
</script>
<td bgcolor="eeeeee">
<b>Mailing Address</b>
<br><br>
<form>
Name:
<input type="text" name="shippingname">
<br>
City:
<input type="text" name="shippingcity">
/>
Checking
/>
Savings
<br>
<input type="checkbox" onclick="FillBilling(this.form)" name="billingtoo">
<em>Check this box if Billing Address and Mailing Address are the same.</em>
<p>
<b>Billing Address</b>
<br><br>
Name:
<input type="text" name="billingname">
<br>
City:
<input type="text" name="billingcity">
/>
Checking
/>
Savings
BUT, I want to add this to the form for both the BILLING and SHIPPING. And then I want the SHIPPING one to match up with the BILLING one if I check the box.
<!-- <td colspan="2"><p>
<label>
<input type="radio" name="acct" value="checking" id="acct_0" <?php if ($user_info['acct'] == "checking"){ echo "checked='checked'"; }?>/>
Checking</label>
<br />
<label>
<input type="radio" name="acct" value="savings" id="acct_1" <?php if ($user_info['acct'] == "savings"){ echo "checked='checked'"; }?>/>
Savings</label>
<br />
</p>
</td>-->
Javascript:
document.getElementById("acct_0").setAttribute("checked", "checked");
Jsfiddle here