Read data from form, and creating object using it - javascript

I have a problem with reading data from my HTML form, and then creating an object using that data. I am making a simple front end portfolio website, and in "Contact" part I would like to manage users to contact me using this form. Here is the code, so if you have any suggestion, please let me know.
This is how I created HTML form and JS:
var users = [];
var createUser = function(){
var form = document.myForm;
//getting data
if(form.name.value == ""){
alert("Please, enter your name.");
}else{
var name = form.name.value;
}
if(form.surname.value == ""){
alert("Please, enter your surname.");
}else{
var surname = form.surname.value;
}
if(form.email.value == ""){
alert("Please, enter your email.");
}else{
var email = form.email.value;
}
if(form.phone.value == ""){
alert("Please, enter your phone number.");
}else{
var phone = form.phone.value;
}
var radSex = form.radSex;
var sex;
for(var i=0; i<radSex.length; i++){
if(radSex[i].checked){
sex = radSex[i].value;
}
}
var radAge = form.radAge;
var age;
for(var i=0; i<radAge.length; i++){
if(radAge[i].checked){
age = radAge[i].value;
}
}
var message = form.getElementByClassName("message").value;
//creating user
var user = {
firstName: name,
lastName: surname,
email: email,
phoneNumber: phone,
sex: sex,
age: age,
message: message
};
//putting into array
users.push(user);
};
function check(){
alert(users[0]);
};
//listening for event
var submitBtn = document.getElementById("submitButton");
submitBtn.addEventListener("click", createUser);
submitBtn.addEventListener("click", check);
<form action="submit" name="myForm">
<p>
<input type="text" name="name" value="Name" class="textbox">
</p>
<p>
<input type="text" name="surname" value="Surname" class="textbox">
</p>
<p>
<input type="text" name="email" value="Email Address" class="textbox">
</p>
<p>
<input type="text" name="phone" value="Phone Number" class="textbox">
</p>
<p>Sex:</p>
<p>
<label>Male </label>
<input type="radio" name="radSex" value="male" checked="checked">
<label> Female </label>
<input type="radio" name="radSex" value="female">
</p>
<p>Age:</p>
<p>
<label><25 </label>
<input type="radio" name="radAge" value="<25" checked="checked">
<label> 25<50 </label>
<input type="radio" name="radAge" value="25<50">
<label> 50<100</label>
<input type="radio" name="radAge" value="50<100">
</p>
<p>
<textarea class="message">Message</textarea>
</p>
<button type="button" class="btn btn-primary btn-block" id="submitButton">Send</button>
</form>

IMO, you should use serialize()
$("form").serialize();
You can select one or more form elements.
Let say, you've large form with lots of fields in it, you can just use the serialize to collect (inputs with name only) all the field values by a single line.
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});

let submitButton = document.querySelector("#submitButton");
submitButton.addEventListener("click",function(){
let nameValue = document.querySelector("[name=name]").value;
let surnameValue = document.querySelector("[name=surname]").value;
let emailValue = document.querySelector("[name=email]").value;
let phoneValue = document.querySelector("[name=phone]").value;
let sexValue = document.querySelector("[name=radSex]").value;
let ageValue = document.querySelector("[name=radAge]").value;
let messageValue = document.querySelector(".message").value;
let backObject = {
"name": nameValue,
"surname": surnameValue,
"email": emailValue,
"phone": phoneValue,
"sex": sexValue,
"age": ageValue,
"message": messageValue
};
console.log(backObject);
});
<form action="submit" name="myForm">
<p>
<input type="text" name="name" value="Name" class="textbox">
</p>
<p>
<input type="text" name="surname" value="Surname" class="textbox">
</p>
<p>
<input type="text" name="email" value="Email Address" class="textbox">
</p>
<p>
<input type="text" name="phone" value="Phone Number" class="textbox">
</p>
<p>Sex:</p>
<p>
<label>Male </label>
<input type="radio" name="radSex" value="male" checked="checked">
<label> Female </label>
<input type="radio" name="radSex" value="female">
</p>
<p>Age:</p>
<p>
<label><25 </label>
<input type="radio" name="radAge" value="<25" checked="checked">
<label> 25<50 </label>
<input type="radio" name="radAge" value="25<50">
<label> 50<100</label>
<input type="radio" name="radAge" value="50<100">
</p>
<p>
<textarea class="message">Message</textarea>
</p>
<button type="button" class="btn btn-primary btn-block" id="submitButton">Send</button>
</form>

Related

How to display form validation error messages accurately for more than two input fields using only JavaScript?

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>

How to stop user for using same username which already exist in my local storage?

var labelsarray = document.getElementsByTagName("label");
var inputsarray = document.getElementsByTagName("input");
var array = [];
function agecal() {
var Bdate = inputsarray[4].value;
var Bday = +new Date(Bdate).getFullYear();
var age = (new Date().getFullYear() - Bday);
inputsarray[5].value = age;
}
function subm() {
var users = {
FirstName: inputsarray[0].value,
LastName: inputsarray[1].value,
UserName: inputsarray[2].value,
Password: inputsarray[3].value,
DateofBirth: inputsarray[4].value,
Age: inputsarray[5].value,
Purpose: ""
};
if (inputsarray[6].checked === true) {
users.Gender = "Male";
} else if (inputsarray[7].checked === true) {
users.Gender = "Female";
}
if (inputsarray[8].checked === true) users.Purpose += " Storing Apps";
if (inputsarray[9].checked === true) users.Purpose += " Storing Sites";
if (inputsarray[10].checked === true) users.Purpose += " Fun";
array.push(users);
localStorage.setItem("Users Data: ", JSON.stringify(array));
var item = localStorage.getItem("Users Data: ");
var arrayobjfromls = JSON.parse(item);
for (var i = 0; i < arrayobjfromls.length; i++) {
if (inputsarray[2].value === arrayobjfromls[i].UserName) {
alert("This username is already in use. Please try another.");
localStorage.removeItem(arrayobjfromls[i]);
}
}
}
<div>
<center>
<form action="javascript:void(0);" method="post" onsubmit="subm();">
<label for="fname">First Name:</label> 
<input type="text" id="fname" />
<br/>
<label for="lname">Last Name:</label> 
<input type="text" id="lname" />
<br/>
<label for="uname">User Name:</label> 
<input type="text" id="uname" />
<br/>
<label for="pass">Password:</label>  
<input type="password" id="pass" />
<br/>
<label for="dob">Date of Birth:</label>  
<input type="date" id="dob" onchange="agecal();" />
<br/>
<label>Age:</label>     
<input type="text" id="age" disabled="disabled" />
<br/>
<span>Gender:</span>     
<input type="radio" name="gender" id="male" />
<label for="male">Male</label>
<input type="radio" name="gender" id="female" />
<label for="female">Female</label>
<br/>
<p>For what purpose(s) you are making account?</p>
<input type="checkbox" id="app" name="purpose" value="storingapps" />
<label for="app">Storing Apps</label>
<input type="checkbox" id="site" name="purpose" value="storingsites" />
<label for="site">Storing Sites</label>
<input type="checkbox" id="fun" name="purpose" value="fun" />
<label for="fun">Fun</label>
<br/>
<input type="submit" value="Submit" class="button" />
</form>
</center>
</div>
Please help me I want to stop user for using username which already present in my local storage by showing an alert and also I don't want to send data to local storage in which username is same of that data which is already present in my local storage...so that my local storage contain only those objects which have different usernames.
You're already checking for this; you're just doing it after you've already added the new user. Do the check first:
var item = localStorage.getItem("Users Data: ");
var arrayobjfromls = JSON.parse(item);
var found = false;
for (var i = 0; i < arrayobjfromls.length; i++) {
if(users.UserName === arrayobjfromls[i].UserName) {
found = true;
break;
}
}
if ( found ) {
alert("This username is already in use. Please try another.");
} else {
array.push( users );
localStorage.setItem("Users Data: ", JSON.stringify(array));
}

javascript - how to get value from input with same name (array)

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.

Why wont my radio button response respond to my Google Spreadsheet?

I've used the following code as a method to send user input data on my html site to a Google Spreadsheet:
Javascript:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
function postContactToGoogle() {
var firstname=$('#firstname').val();
var surname=$('#surname').val();
var dob=$('#dob').val();
var email=$('#email').val();
var option=$('#option').val();
$.ajax({
url:"https://docs.google.com/forms/d/e/1FAIpQLSfe760bJi_65cvSGfu4HckMdmAs1ahBkO7oE6njBTYZh4A/formResponse",
data: {"entry.1012452068":firstname, "entry.1038894874":surname, "entry.1352091133":dob, "entry.1048111489":email, "entry.1786559101":option}, type: "POST", datatype: "xml", statusCode: {0:function() {window.location.replace("thankyou.html");}, 200:function(){window.location.replace("thankyou.html");}}
});
}
</script>
HTML:
<form>
First Name:<br>
<input id="firstname" name="firstname" type="text" placeholder="First Name"/><br>
Surname:<br>
<input id="surname" name="surname" type="text" placeholder="Surname"/><br>
DoB:<br>
<input id="dob" name="dob" type="text" placeholder="DoB"/><br>
Email:<br>
<input id="email" name="email" type="text" placeholder="Email"/><br>
Option Pledge:<br>
<input id="option" name="option" type="radio"/> £49 <br>
<input id="option" name="option" type="radio"/> £69 <br>
<input id="ButtonSubmit" name="" type="button" value="Send" onclick="postContactToGoogle()"/>
</form>
It all works perfectly well except for the last 2 radio button options don't appear on the spreadsheet (shown on the image below). Does anyone have an insight into what I'm doing wrong?
You have 2 issues:
Your radio inputs have the same id="option" and id's should be unique .
Your radio inputs haven't value attribute to send like value="your value".
So this example should work
function postContactToGoogle() {
var firstname = $('#firstname').val();
var surname = $('#surname').val();
var dob = $('#dob').val();
var email = $('#email').val();
var option = $("[name='option']").val();
console.log({
"entry.1012452068": firstname,
"entry.1038894874": surname,
"entry.1352091133": dob,
"entry.1048111489": email,
"entry.1786559101": option
});
alert("your radio button value: " + option);
//it's working..
//then validate your data before sending
$.ajax({
url: "https://docs.google.com/forms/d/e/1FAIpQLSfe760bJi_65cvSGfu4HckMdmAs1ahBkO7oE6njBTYZh4A/formResponse",
data: {
"entry.1012452068": firstname,
"entry.1038894874": surname,
"entry.1352091133": dob,
"entry.1048111489": email,
"entry.1786559101": option
},
type: "POST",
datatype: "xml",
statusCode: {
0: function() {
alert("status:0, thank you");
window.location.replace("thankyou.html");
},
200: function() {
alert("status:200, thank you");
window.location.replace("thankyou.html");
}
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<form>
First Name:
<br>
<input id="firstname" name="firstname" type="text" placeholder="First Name" />
<br>Surname:
<br>
<input id="surname" name="surname" type="text" placeholder="Surname" />
<br>DoB:
<br>
<input id="dob" name="dob" type="text" placeholder="DoB" />
<br>Email:
<br>
<input id="email" name="email" type="text" placeholder="Email" />
<br>Option Pledge:
<br>
<input id="option1" value="Black Ballad Membership - £49" name="option" type="radio" />£49
<br>
<input id="option2" value="Premium Black Ballad Membership - £69" name="option" type="radio" />£69
<br>
<input id="ButtonSubmit" name="" type="button" value="Send" onclick="postContactToGoogle()" />
</form>
Do following change in your code,
var option = $('input[name=option]:checked').val()
Note: There should not be the same id for two different element, you have used id "option" for both radio.

javascript validation - Javascript not running

I'm trying to validate the inputs, so far I've created only two rules. One to test the phone number and another to test if the passwords entered at the same.
My problem is that for some reason my javascript isn't validating input. I have it referenced in <script>, I call it in the form onsubmit="return validate()". For some reason even with using an alert test to check that its run, that fails. So, I'm not really sure what's wrong, I could do with some extra eyes.
function validate() {
var errMsg = ""; /* stores the error message */
var result = true; /* assumes no errors */
var phonetest1 = true;
var phonetest2 = true;
/*get values from the form*/
var FirstName = document.getElementById("FirstName").value;
var Lastname = document.getElementById("Lastname").value;
var Email = document.getElementById("Email").value;
var Password = document.getElementById("Password").value;
var ConPassword = document.getElementById("ConPassword").value;
var Phone = document.getElementById("Phone").value;
var phonepatt1 = (/\(|0|\d|\)|\d|\d|\d|\d|\d|\d|\d|\d/);
var phonepatt2 = (/0|\d|\s|\d|\d|\d|\d|\d|\d|\d|\d/);
/* Rule one */
if (!phonepatt1.test(Phoneno)) {
phonetest1 = false;
}
if (!phonepatt2.test(Phoneno)) {
phonetest2 = false;
}
if (phonetest1 == false && phonetest2 == false) {
errMsg += "Your Phone number is incorrect .\n";
result = false;
}
alert("I'm running"); /* This isn't working */
/* Rule two */
if (ConPassword != Password) {
errMsg += "Please confirm your password .\n";
result = false;
}
if (errMsg != "") { //only display message box if there is something to show
alert(errMsg);
}
return result;
}
<H1>store Home Page</H1>
<p>Customer Registration: Register
<p>Customer Login: Login
<p>Manager Login Administrators
<form id="UserDetails" method="post" onsubmit="return validate()" action="index.htm">
<fieldset id="Details">
<legend>Your details:</legend>
<p>
<label for="FirstName">First Name</label>
<input type="text" name="FirstName" id="FirstName" pattern="[a-zA-Z]+" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Lastname">Last Name</label>
<input type="text" name="LastName" id="Lastname" pattern="[a-zA-Z]+" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Email">Email</label>
<input type="text" name="Email" id="Email" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Password">Password</label>
<input type="text" name="Password" id="Password" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="ConPassword">Confirm Password</label>
<input type="text" name="ConPassword" id="ConPassword" size="20" maxlength="20" required="required" />
</p>
<p>
<label for="Phone">Phone Number</label>
<input type="text" name="Phone" id="Phone" maxlength="12" size="12" placeholder="(03)92251515" />
</p>
<input type="submit" value="Register Now!" />
<input type="reset" value="Reset" />
</fieldset>
</form>
You have wrog name in your JavaScript (should be Phone instead of Phoneno):
if (!phonepatt1.test(Phone)) {
phonetest1 = false;
}
if (!phonepatt2.test(Phone)) {
phonetest2 = false;
}

Categories

Resources