Javascript not working to validate a form in HTML - javascript

Hi i'm having trouble trying to validate a simple form. I'm not the best at Javascript and am unsure where i'm going wrong. It may be a simple speelling mistake or a complete clash between my code that i can't see. All help is appreciated. Sorry for the big chunk of code, i wanted to make sure you see every detail.
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet"
type = "text/css"
href = "Stylesheet.css" />
<title>Customer details form</title>
<script src="gen_validatorv4.js" type="text/javascript"></script>
<!-- ============================== My failed attempt to try and validate my form with Javascript ============================== -->
<script>
function check() {
document.getElementById("Agree").checked = true;
}
function uncheck() {
document.getElementById("Agree").checked = false;
}
</script>
<center><img src= Images/HorizonHomePageTitle.png ALT="Horizon Bed and Breakfast Title"></center>
</head>
<body>
<script>
window.alert(Please enter data where * is assigned.);
</script>
<center>Budget Rooms<center>
<HR COLOR="blue" WIDTH="60%">
<center>Luxury Rooms<center>
<HR COLOR="blue" WIDTH="60%">
<center>Home<center>
<HR COLOR="blue" WIDTH="60%">
<center>Our privacy policy<center>
<HR COLOR="blue" WIDTH="60%">
<center>Our terms of conditions<center>
<HR COLOR="blue" WIDTH="60%">
<center>Our terms and conditions<center>
<HR COLOR="blue" WIDTH="60%">
<center>Contact us<center>
<form id='CustomerDetailForm' action="">
<!-- ============================== Fieldset 1 - includes personal information of clients ============================== -->
<fieldset>
<legend>Personal Information:</legend>
<hr class="form" />
<label for="Full Name"><strong>Full Name:*</strong></label>
<input name="FullNm" type="text" size="20" id="FN" class="text"/>
<label for="Email"><strong>Email:</strong></label><br/>
<input name="Emil" type="text" size="20" id="EM" class="text"/>
<label for="Age"><strong>Input age if between 18 and 100:</strong></label>
<input name="Ages" type="text" size="20" id="AG" class="text"/>
<label for="select" class="choose"><strong>On what continent do you live?</strong></label>
<select id="select" name="select">
<option value="1">Africa</option>
<option value="2">Europe</option>
<option value="3">Asia</option>
<option value="4">North Amrica</option>
<option value="5">South America</option>
<option value="6">Ausralia</option>
</select>
</fieldset>
<!-- ============================== Fieldset 2 - Includes further optional information from clients to help productivity ============================== -->
<fieldset>
<legend>Questions:</legend>
<hr class="form" />
<label for="select2" class="choose">How long was your stay?</label><br />
<select id="select" name="select2">
<option value="7">Less than one week</option>
<option value="8">More than one week</option>
<option value="9">Months/years</option>
</select>
<label for="select3" class="choose">How many stars would you rate our BnB?</label><br />
<select id="selectCon" name="select3">
<option value="10">One star</option>
<option value="11">Two star</option>
<option value="12">Three star</option>
<option value="13">Four star</option>
<option value="14">Five star</option>
</select>
</fieldset>
<!-- ============================== Fieldset 3 - Holds the comments section, aggreement radio button, submit button and a date button for the client ============================== -->
<fieldset>
<legend>Further commetns:</legend>
<hr class="form" />
<textarea name="message" id="message" cols="20" rows="10"></textarea><br />
<label for="protection" class="spam-protection">Spam check: 1 + 1=</label><br />
<input name="ochrana" type="text" id="protection" class="answer" /><br />
Do you agree to our terms?*<br>
<input type="radio" name="Agreement" id="Agree">Agree<br>
<button onclick="formValidation()">SUBMIT</button>
<script>
function submitFunction() {
alert("Thankyou for your submission");
}
</script>
<script>
function formValidation()
{
var uname = document.registration.FullNm;
var uemail = document.registration.Emil;
var uage = document.registration.Ages;
var ucon = document.registration.select;
{
if(nameinput(FullName,2,25))
{
if(emailval(uemail))
{
if(agenum(ag))
{
if(conselect(con))
{
}
}
}
}
}
}
}
}
return false;
}
function nameinput(uname,2,25)
{
var uname_len = uname.value.length;
if (uname_len == 0 || uname_len >= 2 || uname_len < 25)
{
alert("Full Name is needed. Between "+2+" to "+25" characters.);
uname.focus();
return false;
}
return true;
}
function emailval(uemail,2,25)
{
var uemail_len = uemail.value.length;
if (uemail_len == 0 || uemail_len >= 2 || uemail_len < 30)
{
alert("Email is required.");
uemail.focus();
return false;
}
return true;
}
function agenum(uage,18,100)
{
var uage_len = uage.value.length;
if (uage_len == 0 || uage_len >= 18 || uage_len < 100)
{
alert("Age is required. Between 18 and 100.");
uage.focus();
return false;
}
return true;
}
function conselect(ucon)
{
if(ucon.value == "Default")
{
alert('Select your continent from the list');
ucon.focus();
return false;
}
else
{
return true;
}
}
</script>
</form>
<button type="button"
onclick="document.getElementById('date/time').innerHTML = Date()">
Display date and time.</button>
<p id="date/time"></p>
</fieldset>
</form>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Stylesheet.css" />
<title>Customer details form</title>
<script src="gen_validatorv4.js" type="text/javascript"></script>
<!-- ============================== My failed attempt to try and validate my form with Javascript ============================== -->
<script type="text/javascript">
function check() {
document.getElementById("Agree").checked = true;
}
function uncheck() {
document.getElementById("Agree").checked = false;
}
function formValidation() {
var uname = document.getElementById("FullNm");
var uemail = document.getElementById("Email");
var uage = document.getElementById("Ages");
var ucon = document.getElementById("select1");
if (nameInput(uname)) {
if (emailVal(uemail)) {
if (ageNum(uage)) {
if (conSelect(ucon)) {
}
}
}
}
}
function nameInput(uname) {
var uname_len = uname.value.length;
if (uname_len == 0 || uname_len <= 2 || uname_len > 25) {
alert("Full Name is needed. Between 2 to 25 characters.");
uname.focus();
return false;
}
else {
return true;
}
}
function emailVal(uemail) {
var uemail_len = uemail.value.length;
if (uemail_len == 0) {
alert('Email is required');
return false;
}
else {
return true;
}
}
function ageNum(uage) {
var age = uage.value;
if (age == 0 || age < 18 || age > 100) {
alert("Age is required. Between 18 and 100.");
uage.focus();
return false;
}
else
return true;
}
function conSelect(ucon) {
if (ucon.value == 0) {
alert('Select your continent from the list');
ucon.focus();
return false;
}
else {
return true;
}
}
</script>
<center>
<img src="Images/HorizonHomePageTitle.png" alt="Horizon Bed and Breakfast Title"></center>
</head>
<body>
<center>
Budget Rooms<center>
<hr color="blue" width="60%">
<center>
Luxury Rooms<center>
<hr color="blue" width="60%">
<center>
Home<center>
<hr color="blue" width="60%">
<center>
<a href="https://www.visser.com.au/blog/generic-privacy-policy-for-australian-websites/"
target="_blank">Our privacy policy</a><center>
<hr color="blue" width="60%">
<center>
<a href="https://media.termsfeed.com/pdf/terms-and-conditions-template.pdf" target="_blank">
Our terms of conditions</a><center>
<hr color="blue" width="60%">
<center>
<a href=" http://www.blogtyrant.com/best-about-us-pages/" target="_blank">Our terms
and conditions</a><center>
<hr color="blue" width="60%">
<center>
Contact us<center>
<form id='CustomerDetailForm' action="">
<!-- ============================== Fieldset 1 - includes personal information of clients ============================== -->
<fieldset>
<table>
<tr>
<td colspan="2">
<legend>Personal Information:</legend>
</td>
</tr>
<tr>
<td>
<label for="Full Name">
<strong>Full Name:*</strong></label>
</td>
<td>
<input id="FullNm" name="FullNm" type="text" size="20" class="text" />
</td>
</tr>
<tr>
<td>
<label for="Email">
<strong>Email:</strong></label><br />
</td>
<td>
<input id="Email" name="Email" type="text" size="20" class="text" />
</td>
</tr>
<tr>
<td>
<label for="Age">
<strong>Input age if between 18 and 100:</strong></label>
</td>
<td>
<input name="Ages" type="text" size="20" id="Ages" class="text" />
</td>
</tr>
<tr>
<td>
<label for="select" class="choose">
<strong>On what continent do you live?</strong></label>
</td>
<td>
<select id="select1" name="select">
<option value="0">Select</option>
<option value="1">Africa</option>
<option value="2">Europe</option>
<option value="3">Asia</option>
<option value="4">North Amrica</option>
<option value="5">South America</option>
<option value="6">Ausralia</option>
</select>
</td>
</tr>
</table>
</fieldset>
<!-- ============================== Fieldset 2 - Includes further optional information from clients to help productivity ============================== -->
<fieldset>
<legend>Questions:</legend>
<hr class="form" />
<label for="select2" class="choose">
How long was your stay?</label><br />
<select id="select" name="select2">
<option value="7">Less than one week</option>
<option value="8">More than one week</option>
<option value="9">Months/years</option>
</select>
<label for="select3" class="choose">
How many stars would you rate our BnB?</label><br />
<select id="selectCon" name="select3">
<option value="10">One star</option>
<option value="11">Two star</option>
<option value="12">Three star</option>
<option value="13">Four star</option>
<option value="14">Five star</option>
</select>
</fieldset>
<!-- ============================== Fieldset 3 - Holds the comments section, aggreement radio button, submit button and a date button for the client ============================== -->
<fieldset>
<legend>Further commetns:</legend>
<hr class="form" />
<textarea name="message" id="message" cols="20" rows="10"></textarea><br />
<label for="protection" class="spam-protection">
Spam check: 1 + 1=</label><br />
<input name="ochrana" type="text" id="protection" class="answer" /><br />
Do you agree to our terms?*<br>
<input type="radio" name="Agreement" id="Agree">Agree<br>
<button onclick="formValidation();">
SUBMIT</button>
</fieldset>
</form>
<script type="text/javascript">
function submitFunction() {
alert("Thankyou for your submission");
}
</script>
<button type="button" onclick="document.getElementById('date/time').innerHTML = Date()">
Display date and time.</button>
<p id="date/time">
</p>
</body>
</html>

Related

How do I add checks to make the code to display 'Password too short' and 'Height is not a number?'

I have to add checks to the checkSubmit() function so that it will give the following response
Passwords do not match
Passwords is too short(minimum 4 characters)
Height is not a number
I have managed the first one however I have no idea where to start with the other two. I'll post all the code just to be safe in case I missed something.
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>Form Validation</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="styles/styles.css">
<link rel="stylesheet" type="text/css" href="styles/forms.css">
<script type="text/javascript">
window.onload=init;
var form;
function init() {
form = document.getElementById('testform');
form.addEventListener("submit", checkSubmit, false);
form.addEventListener("reset", checkReset, false);
form['colour'].addEventListener("change", checkSubmit, false);
form['name'].focus();
}
String.prototype.trim=function() {
return this.replace(/^\s+1\s+$/g, '');
}
function whichButton(name) {
var buttons=document.getElementsByName(name);
for (var i in buttons) {
if(buttons[i].checked) return buttons[i].value
}
return false;
}
function showOtherColour() {
document.getElementById('othercolour').style.visibility=
form['colour'].value=='other' ? 'visible' : 'hidden';
}
function checkSubmit() {
error = new Array();
//Fill the array with the error value
form['name'].value=form['name'].value.trim();
form['email'].value=form['email'].value.trim();
form['town'].value=form['town'].value.trim();
form['state'].value=form['state'].value.trim();
form['postcode'].value=form['postcode'].value.trim();
form['dob'].value=form['dob'].value.trim();
form['height'].value=form['height'].value.trim();
//Check required fields
if(!form['name'].value)
error.push('Missing Name');
if(!form['email'].value)
error.push('Missing Email Address');
if(!form['password'].value)
error.push('Missing Password');
//Check valid email address
var pattern=/^[a-zA-Z0-9._%-]+#[a-zA-Z0-9.-]+(\.[a-zA-Z]{2,4})$/;
if(!form['email'].value.match(pattern))
error.push('Invalid Email Address');
//Check State
//Check Post Code has 4 digits
var pattern=/^\d{4}$/;
if(!form['postcode'].value.match(pattern))
error.push('Invalid Post Code');
//Check password matches confirmation
//var password = ;
/*
if(!form['passwordConfirm'].value.match(password)){
error.push("Passwords don't match");
}*/
console.log(form['confirm'].value);
console.log(form['password'].value);
if(!form['confirm'].value.match(form['password'].value)){
error.push('Passwords do not match');
}
//Check that one Gender item is selected
if(whichButton('gender')===false)
error.push('Please choose a Gender');
//Check that "Other" field is filled
if (!form['colour'].value ||
(form['colour'].value=='other' && !form['othercolour'].value))
error.push('Colour is not selected');
if(error.length) { // if there are errors
alert(error.join("\n"))
return false;
}
else return true;
//return confirm("This will submit the form"); //Temporary placeholder
}
function checkReset() {
return confirm("This will clear the form data");
}
</script>
<style type="text/css">
body,td,th {
font-size: 0.9em;
}
</style>
</head>
<body>
<div id="body">
<h1>Form Validation</h1>
<form action="http://test.miform.net" method="post" id="testform">
<fieldset>
<label>Name<br><input type="text" name="name" class="wide"></label>
<label>Email Address<br><input type="text" name="email" class="wide"></label>
</fieldset>
<fieldset>
<label>Address<br><input type="text" name="street" class="wide"></label>
<label>Town<br><input type="text" name="town" class="narrow"></label>
<label>State<br><input type="text" name="state" class="narrow"></label>
<label>PostCode<br><input type="text" name="postcode" class="narrow"></label>
</fieldset>
<fieldset>
<label>Password<br><input type="password" name="password" class="medium"></label>
<label>Confirm Password<br><input type="password" name="confirm" class="medium"></label>
</fieldset>
<fieldset>
<label>Date of Birth<br><input type="text" name="dob" class="medium"></label>
<label>Height<br><input type="text" name="height" class="medium"></label>
</fieldset>
<fieldset>
<legend>Gender</legend>
<label><input type="radio" name="gender" value="f">Female</label>
<label><input type="radio" name="gender" value="m">Male</label>
</fieldset>
<fieldset>
<label>Colour
<select name="colour">
<option value="">Select...</option>
<option value="black">Black</option>
<option value="white">White</option>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="cyan">Cyan</option>
<option value="magenta">Magenta</option>
<option value="yellow">Yellow</option>
<option value="other">Other</option>
</select>
</label>
<input type="text" id="othercolour">
</fieldset>
<input type="reset" name="reset" value="Clear Form">
<input type="submit" name="send" value="Send Off">
</form>
</div>
</body>
</html>
Do this for the second:
if (form['password'].value.length < 4) {
error.push("Password is too short");
}
And this for the third:
if (isNan(Number(form['height'].value))) {
error.push("Height is not a number");
}

Do not repeat yourself best practices showing and hiding fields

I am trying to figure out the best way to show and hide fields that are being reused. Cleaning up the code so that I do not repeat myself "DRY". Will someone please assist me in the best practices of doing so?
What I have is a select that allows the user to choose from two different reports.
<select class="form-control" id="reporttype" name="reporttype">
<option value="" selected="selected">Select Report</option>
<option id ="checklistreport" value="checklistreport" >Checklist Stats</option>
<option id ="locationreport" value="locationreport" >Location Stats</option>
</select>
Then each report have a lot of similar fields. How can I have them use the same fields but hide/show the differences and go to the correct form "action" based which report is chosen.
Location Report
<form name="generatereport" method="post" action="_location_queries.cfm">
<select name="Location" id="loc" multiple="multiple" required size="9">
<option value="OPERATIONS">Operations</option>
<option value="CCC">Contact Center</option>
<option value="QA">QA Department</option>
<option value="DS">DeSoto</option>
<option value="PS">Palma Sola</option>
<option value="LWR">Lakewood Ranch</option>
<option value="NR">North River</option>
<option value="SDL">SDL</option>
<option value="FSC">FSC</option>
</select>
<button id="add" type="button">ADD ALL</button>
<button id="rem" type="button">REMOVE ALL</button>
<textarea id="selected" rows="10" readonly></textarea>
<br /><br />
<label for="StartDate">From</label>
<input type='text' name="StartDate" id="StartDate" value="" required/>
<br /><br />
<label for="EndDate">To</label>
<input type='text' name="EndDate" id="EndDate" value="" required/>
<br /><br />
<label for="Format">Format</label>
<select name="Format" required>
<option selected value="">Select Format</option>
<option value="print">Print</option>
<option value="pdf">Preview</option>
<option value="xls">Excel</option>
</select>
<br /><br />
<input type="submit" name="submit" value="Continue" />
</form>
<script type="text/javascript">
var opts = document.querySelectorAll('#loc option');
document.getElementById('add').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = true;
}
reflectChange();
});
document.getElementById('rem').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = false;
}
reflectChange();
});
document.getElementById('loc').addEventListener('change', reflectChange);
function reflectChange() {
document.getElementById('selected').value = '';
for ( var i=0; i<opts.length; i++ ) {
if(opts[i].selected)
document.getElementById('selected').value += opts[i].text+'\n';
}
}
</script>
Checklist Report
<form name="generatereport" method="post" action="_checklists_queries.cfm">
<select name="Location" id="loc" multiple="multiple" required size="8">
<option value="OPERATIONS">Operations</option>
<option value="CCC">Contact Center</option>
<option value="QA">QA Department</option>
<option value="DS">DeSoto</option>
<option value="PS">Palma Sola</option>
<option value="LWR">Lakewood Ranch</option>
<option value="NR">North River</option>
<option value="SDL">SDL</option>
<option value="FSC">FSC</option>
</select>
<button id="add" type="button">ADD ALL</button>
<button id="rem" type="button">REMOVE ALL</button>
<textarea id="selected" rows="7" readonly></textarea>
<br /><br />
<cfquery name="GetActiveEmps" datasource="tco_associates">
SELECT assoc_userid, assoc_last, assoc_first FROM tco_associates
WHERE assoc_status = 'ACTIVE'
and assoc_last NOT LIKE 'Test%'
and len(assoc_last) > 0
ORDER BY assoc_last
</cfquery>
<select name="EmployeeName" id="EmployeeName" multiple="multiple" required size="8">
<cfoutput query="GetActiveEmps">
<option value="#assoc_userid#">#Trim(assoc_last)#, #Trim(assoc_first)#</option>
</cfoutput>
</select>
<button id="add1" type="button">ADD ALL</button>
<button id="rem1" type="button">REMOVE ALL</button>
<textarea id="selected1" rows="7" readonly></textarea>
<br /><br />
<label for="StartDate">From</label>
<input type='text' name="StartDate" id="StartDate" value="" required/>
<br /><br />
<label for="EndDate">To</label>
<input type='text' name="EndDate" id="EndDate" value="" required/>
<br /><br />
<label for="Format">Format</label>
<select name="Format" required>
<option selected value="">Select Format</option>
<option value="print">Print</option>
<option value="pdf">Preview</option>
<option value="xls">Excel</option>
</select>
<br /><br />
<input type="submit" name="submit" value="Continue" />
</form>
<script type="text/javascript">
// JS for Showing Chosen Locations in textarea
var opts = document.querySelectorAll('#loc option');
document.getElementById('add').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = true;
}
reflectChange();
});
document.getElementById('rem').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = false;
}
reflectChange();
});
document.getElementById('loc').addEventListener('change', reflectChange);
function reflectChange() {
document.getElementById('selected').value = '';
for ( var i=0; i<opts.length; i++ ) {
if(opts[i].selected)
document.getElementById('selected').value += opts[i].text+'\n';
}
}
// End JS for Showing Chosen Locations in textarea
// JS for Showing Chosen Associates in textarea
var opts1 = document.querySelectorAll('#EmployeeName option');
document.getElementById('add1').addEventListener('click', function() {
for ( var i=0; i<opts1.length; i++ ) {
opts1[i].selected = true;
}
reflectChange1();
});
document.getElementById('rem1').addEventListener('click', function() {
for ( var i=0; i<opts1.length; i++ ) {
opts1[i].selected = false;
}
reflectChange1();
});
document.getElementById('EmployeeName').addEventListener('change', reflectChange1);
function reflectChange1() {
document.getElementById('selected1').value = '';
for ( var i=0; i<opts1.length; i++ ) {
if(opts1[i].selected)
document.getElementById('selected1').value += opts1[i].text+'\n';
}
}
// End JS for Showing Chosen Associates in textarea
</script>
Many of these fields are the same is there a way i can just have one set and show them if either option is chosen and not have two different sets?
This is what I have tried:
<select class="form-control" id="reporttype" name="reporttype">
<option value="" selected="selected">Select Report</option>
<option id ="checklistreports" value="checklistreports" >Checklist Stats</option>
<option id ="locationreports" value="locationreports" >Location Stats</option>
</select>
<script>
$(document).on('change', '#reporttype', function() {
var value = $(this).val();
//var checklistreport = $("#checklistreport");
//var locationreport = $("#locationreport");
var location = $("#location");
var employeelist = $("#employeelist");
var chosendates = $("#chosendates");
var formattype = $("#formattype");
var submitbtn = $("#submitbtn");
if (value == "checklistreports") {
//checklistreport.show();
//locationreport.hide();
location.show();
employeelist.show();
chosendates.show();
formattype.show();
submitbtn.show();
} else if (value == "locationreports") {
//checklistreport.hide();
//locationreport.show();
location.show();
employeelist.hide();
chosendates.show();
formattype.show();
submitbtn.show();
} else {
//checklistreport.hide();
//locationreport.hide();
location.hide();
employeelist.hide();
chosendates.hide();
formattype.hide();
submitbtn.hide();
}
});
</script>
<br /><br />
<!--<div id="locationreport" style="display: none;">-->
<form name="generatereport" method="post" action="_location_queries.cfm">
<!--<div id="checklistreport" style="display: none;">-->
<form name="generatereport" method="post" action="_checklists_queries.cfm">
</form>
<div id="location" style="display: none;">
<select name="Location" id="loc" multiple="multiple" required size="9">
<option value="OPERATIONS">Operations</option>
<option value="CCC">Contact Center</option>
<option value="QA">QA Department</option>
<option value="DS">DeSoto</option>
<option value="PS">Palma Sola</option>
<option value="LWR">Lakewood Ranch</option>
<option value="NR">North River</option>
<option value="SDL">SDL</option>
<option value="FSC">FSC</option>
</select>
<button id="add" type="button">ADD ALL</button>
<button id="rem" type="button">REMOVE ALL</button>
<textarea id="selected" rows="10" readonly></textarea>
</div>
<br /><br />
<div id="employeelist" style="display: none;">
<cfquery name="GetActiveEmps" datasource="tco_associates">
SELECT assoc_userid, assoc_last, assoc_first FROM tco_associates
WHERE assoc_status = 'ACTIVE'
and assoc_last NOT LIKE 'Test%'
and len(assoc_last) > 0
ORDER BY assoc_last
</cfquery>
<select name="EmployeeName" id="EmployeeName" multiple="multiple" required size="9">
<cfoutput query="GetActiveEmps">
<option value="#assoc_userid#">#Trim(assoc_last)#, #Trim(assoc_first)#</option>
</cfoutput>
</select>
<button id="add1" type="button">ADD ALL</button>
<button id="rem1" type="button">REMOVE ALL</button>
<textarea id="selected1" rows="10" readonly></textarea>
</div>
<br /><br />
<div id="chosendates" style="display: none;">
<label for="StartDate">From</label>
<input type='text' name="StartDate" id="StartDate" value="" required/>
<br /><br />
<label for="EndDate">To</label>
<input type='text' name="EndDate" id="EndDate" value="" required/>
</div>
<br /><br />
<div id="formattype" style="display: none;">
<label for="Format">Format</label>
<select name="Format" required>
<option selected value="">Select Format</option>
<option value="print">Print</option>
<option value="pdf">Preview</option>
<option value="xls">Excel</option>
</select>
</div>
<br /><br />
<div id="submitbtn" style="display: none;">
<input type="submit" name="submit" value="Continue" />
</div>
</form>
<script type="text/javascript">
// JS for Showing Chosen Locations in textarea
var opts = document.querySelectorAll('#loc option');
document.getElementById('add').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = true;
}
reflectChange();
});
document.getElementById('rem').addEventListener('click', function() {
for ( var i=0; i<opts.length; i++ ) {
opts[i].selected = false;
}
reflectChange();
});
document.getElementById('loc').addEventListener('change', reflectChange);
function reflectChange() {
document.getElementById('selected').value = '';
for ( var i=0; i<opts.length; i++ ) {
if(opts[i].selected)
document.getElementById('selected').value += opts[i].text+'\n';
}
}
// End JS for Showing Chosen Locations in textarea
// JS for Showing Chosen Associates in textarea
var opts1 = document.querySelectorAll('#EmployeeName option');
document.getElementById('add1').addEventListener('click', function() {
for ( var i=0; i<opts1.length; i++ ) {
opts1[i].selected = true;
}
reflectChange1();
});
document.getElementById('rem1').addEventListener('click', function() {
for ( var i=0; i<opts1.length; i++ ) {
opts1[i].selected = false;
}
reflectChange1();
});
document.getElementById('EmployeeName').addEventListener('change', reflectChange1);
function reflectChange1() {
document.getElementById('selected1').value = '';
for ( var i=0; i<opts1.length; i++ ) {
if(opts1[i].selected)
document.getElementById('selected1').value += opts1[i].text+'\n';
}
}
// End JS for Showing Chosen Associates in textarea
</script>
Not sure how I choose which action for the form. Depending on which report is chosen.
https://jsfiddle.net/bobrierton/o2gxgz9r/10018/
You have a few options here:
Option #1:
Always show the "common" inputs, and only hide the inputs that are conditional upon selection, that way your code is cleaner because you only have to manage the conditional elements (not all of them as you are doing now)
Option #2:
Use CF includes to hold your "common" elements, and "conditional" elements, combining them where necessary to build the correct list.
Option #3:
Use JavaScript to hold your "common" elements, and "conditional" elements, and render the composed list based on your conditions.
var location = $('select[name=Location]');
// This lists could hold anything you want, jQuery elements
// references, strings, etc.
var lists = {
common: ['a', 'b', 'c'],
locationreports: ['location #1', 'location #2'],
checklistreports: ['checklist #1', 'checklist #2']
};
$('#reporttype').on('change', function() {
var value = $(this).val();
// Grab a copy of the common list to begin with
var options = [].concat(lists.common);
// Now combine the conditional options
if (value === "checklistreports" || value === "locationreports") {
options = options.concat(lists[value]);
}
// Now you have a complete list of options to show based
// your conditions, so now you can just show them all, or
// do whatever you want with this new list.
location.empty();
options.forEach(function($element) {
// Do something with the list
location.append('<option value="' + $element + '">' + $element + '</option>');
})
There are lots of other options, but between using and combining includes, or composing objects together you should be able to customize a nice DRY workflow.

Jquery's form serialization sends repeated information

I send form data using Jquery's $("form").serialize() method. I display the serialized data as alert($("form").serialize()); and found some repeated messages.
What could be the problem there?
The logged message is shown in the attached image.
There are repeated data (underlined). The first one is fine stories=3&bedrooms=2&bathrooms=2 for three SELECT elements. Then there is another repeated message with bedrooms=Bedrooms&bathroom=Bathrooms, then my PHP code at server caught the second one and the value is never changed.
stories=3&bedrooms=2&bathrooms
are three SELECT elements and their default options for bedrooms and bathrooms are Bedrooms and Bathrooms. Because of the repeated data, no matter I change other options at bedrooms and bathrooms, the value sent to server is never changed.
What could be the problem and how to solve?
Thanks
EDIT:
My HTML code is long. I am just beginner for Webapplications, not sure they are in appropriate way, anyway they are as follow. There are two steps validations, one at client side in the function function validatelanded( event ) and another one at server function sendtoServer().
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<style type="text/css">
#header { background-color:green; color:white; text-align:center; padding:5px;}
#background {background: url(register_background.png);}
body {
background-color: #cccccc;
}
.star { color: red;}
.button { background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer;
}
.button2:hover { box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24),0 17px 50px 0 rgba(0,0,0,0.19);}
.overflow { height: 200px; }
select[required] + label {
color: #999;
font-family: Arial;
font-size: 17px;
position: relative;
/*left: -230px; the negative of the input width */
}
select[required] + label:after {
content:'*';
color: red;
}
input[required] + label {
color: #999;
font-family: Arial;
font-size: 17px;
position: relative;
/*left: -230px; the negative of the input width */
}
input[required] + label:after {
content:'*';
color: red;
}
input[need] + text{
color: #999;
font-family: Arial;
font-size: 17px;
position: relative;
/*left: -230px; the negative of the input width */
}
</style>
</head>
<body>
<div id="header">
<h1>Please add your landed property to advertise</h1>
</div>
<div id="background">
<form name="advertiseForm" id="advertiseForm" method="post" >
<br /><br />
<div class="form_box">
<div class="input_box ">
<input type="radio" name="purpose" value="Sell" >To sell
<input type="radio" name="purpose" value="Rent" required="required">To rent
<label for="purpose">Please select transaction type</label>
<div id="purpose-error" class="error-box" style="color:#FF0000">
</div>
</div>
<div class="clear"></div>
</div>
<br /><br />
<div class="form_box">
<div class="input_box ">
<input class="type" type="radio" name="type" value="No_building" >No building
<input class="type" type="radio" name="type" value="With_RC">With RC
<input class="type" type="radio" name="type" value="With_BrickNorcal" required="required">With BrickNorcal
<label for="type">Please select building type</label>
<div id="type-error" class="error-box" style="color:#FF0000"></div>
</div>
<div class="clear"></div>
</div>
<br /><br /><br />
<select name="stories" id="stories" required="required"/>
<option value="Stories" >Number of stories</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="morethan4">More than 4</option>
<select/>
<label for="stories">Please select for number of stories</label>
<div id="stories-error" class="error-box" style="color:#FF0000"></div>
<br /><br /><br />
<select name="bedrooms" id="bedrooms" required="required"/>
<option value="Bedrooms" >Number of bedrooms</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<select/>
<label for="numbedrooms">Please select for number of bedrooms</label>
<div id="bedrooms-error" class="error-box" style="color:#FF0000"></div>
<br /><br /><br />
<select name="bathrooms" id="bathrooms" required="required"/>
<option value="Bathrooms" >Number of Bathrooms</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<select/>
<label for="bathrooms">Please select for number of bathrooms</label>
<div id="bathrooms-error" class="error-box" style="color:#FF0000"></div>
<br /><br /><br />
<select name="divs_states" id="divs_states" required="required"/>
<optgroup label="Divisions">
<option value="Division">Please select one of the following divisions</option>
<option value="jquery">jQuery.js</option>
<option value="jqueryui">ui.jQuery.js</option>
</optgroup>
<optgroup label="States">
<option value="State">Please select one of the following states</option>
<option value="somefile">Some unknown file</option>
<option value="someotherfile">Some other file with a very long option text</option>
</optgroup>
<select/>
<label for="divs_states">Please select a region</label>
<div id="divs_states-error" class="error-box" style="color:#FF0000"></div>
<br /><br /><br />
<select name="township" id="township" required="required"/>
<option value="Township" >Township</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
<select/>
<label for="township">Please select a nearest township</label>
<div id="township-error" class="error-box" style="color:#FF0000"></div>
<br /><br /><br />
<div class="form_box">
<div class="input_box">
<input maxlength="100" type="price" name="price" id="price" required="required" />
<label for="price">Price</label>
<div id="price-error" class="error-box" style="color:#FF0000"></div>
</div>
<div class="clear"></div>
</div>
<br /><br />
<div class="form_box">
<div class="input_box">
<input maxlength="100" type="length" name="length" id="length" required="required" />
<label for="length">Length in feet</label>
<input maxlength="100" type="width" name="width" id="width" required="required" />
<label for="width">Width in feet</label>
<br />
<div id="length-error" class="error-box" style="color:#FF0000"></div>
<div id="width-error" class="error-box" style="color:#FF0000"></div>
</div>
<div class="clear"></div>
</div>
<br />
<input type="radio" name="havetelephone" value="yes" checked>Yes
<input type="radio" name="havetelephone" value="no" need="need">No
<text for="havetelephone">Landline telephone installed at home?</text>
<br /><br />
<input type="radio" name="haveaircon" value="yes">Yes
<input type="radio" name="haveaircon" value="no" required="required">No
<label for="haveaircon">Aircon installed?</label>
<div id="haveaircon-error" class="error-box" style="color:#FF0000"></div>
<br /><br /><br />
<select name="possession" required="required"/>
<option value="Possession" >Possession</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
<select/>
<label for="possession">Please select a possession type</label>
<div id="possession-error" class="error-box" style="color:#FF0000"></div>
<br /><br /><br />
<input maxlength="100" type="text" name="date" id="date" required="required" />
<label for="date">Please specify an available date for start use</label>
<div id="date-error" class="error-box" style="color:#FF0000"></div>
<br /><br /><br />
<textarea rows="20" cols="70" name="textarea" id="textarea" placeholder="Please enter additional information here..."></textarea>
<div id="textarea-error" class="error-box" style="color:#FF0000"></div>
<br /><br />
<div style="color:#0000FF">
<h3>Contact address</h3>
</div>
<br />
<input type="radio" name="agentowner" value="Agent" >Agent
<input type="radio" name="agentowner" value="Owner" required="required">Owner
<label for="agentowner">Please specify</label>
<div id="agentowner-error" class="error-box" style="color:#FF0000"></div>
<br /><br />
<div class="form_box">
<div class="input_box ">
<input maxlength="60" type="text" name="name" id="name" required="required" />
<label for="name">Name</label>
<div id="name-error" class="error-box" style="color:#FF0000"></div>
</div>
<div class="clear"></div>
</div>
<br /><br />
<div class="form_box">
<div class="input_box ">
<input maxlength="60" type="text" name="phone" id="phone" required="required" />
<label for="phone">Phone</label>
<div id="phone-error" class="error-box" style="color:#FF0000"></div>
</div>
<div class="clear"></div>
</div>
<br /><br />
<div class="form_box">
<div class="input_box">
<input maxlength="64" type="text" name="email" id="email" required="required" />
<label for="email">Email</label>
<div id="email-error" class="error-box" style="color:#FF0000"></div>
</div>
<div class="clear"></div>
</div>
<br /><br />
<textarea rows="10" cols="50" name="address" id="address" placeholder="Please key in full address if you are ok..."></textarea>
<!-- Check on the page itself first -->
<br /><br /><br />
<div style="text-align:center">
<input class="button button2" id="submitbutton" type="button" value="Submit" />
</div>
</form>
</div>
</body>
<script>
$("#textarea")
.focus(function() {
if ($("#textarea").val() == null) return;
if ($("#textarea").val() == "Please enter additional information here...")
$("#textarea").val('');
})
.blur(function() {
if ($("#textarea").val() == null) return;
if ($("#textarea").val() == '')
$("#textarea").val('Please enter additional information here...');
});
$("#address")
.focus(function() {
if ($("#address").val() == null) return;
if ($("#address").val() == "Please key in full address if you are ok...")
$("#address").val('');
})
.blur(function() {
if ($("#address").val() == null) return;
if ($("#address").val() == '')
$("#address").val('Please key in full address if you are ok...');
});
$(function() {
$( "#date" ).datepicker();
});
function trimAll( str ) {
return str.replace( /^\s+|\s+$/g, '' );
}
function sendtoServer() {
alert($("form").serialize());
$.ajax({
url: "advertisementdatavalidationatserver.php",
type: "POST",
data: $("form").serialize(),
success: function(ret){
alert(ret);
if(ret.error == true){
if(ret.message.indexOf("Purposeerror")>=0){
$('#purpose-error').css('display', 'block');
$('#purpose-error').html('Please enter to rent or to sell');
}else{
$('#purpose-error').html('');
}
if(ret.message.indexOf("Typeerror")>=0){
$('#type-error').css('display', 'block');
$('#type-error').html('Please enter your building type');
}else{
$('#type-error').html('');
}
if(ret.message.indexOf("Storieserror")>=0){
$('#stories-error').css('display', 'block');
$('#stories-error').html('Please enter number of stories at your building');
}else{
$('#stories-error').html('');
}
if(ret.message.indexOf("Bedroomserror")>=0){
$('#bedrooms-error').css('display', 'block');
$('#bedrooms-error').html('Please enter number of bedrooms at your building');
}else{
$('#bedrooms-error').html('');
}
if(ret.message.indexOf("Bathroomserror")>=0){
$('#bathrooms-error').css('display', 'block');
$('#bathrooms-error').html('Please enter number of bathrooms at your building');
}else{
$('#bathrooms-error').html('');
}
if(ret.message.indexOf("Divisionerror")>=0){
$('#divs_states-error').css('display', 'block');
$('#divs_states-error').html('Please select a Division or a State');
}else{
$('#divs_states-error').html('');
}
if(ret.message.indexOf("Townshiperror")>=0){
$('#township-error').css('display', 'block');
$('#township-error').html('Please select a Township');
}else{
$('#township-error').html('');
}
if(ret.message.indexOf("Priceerror")>=0){
$('#price-error').css('display', 'block');
$('#price-error').html('Please include the price');
}else{
$('#price-error').html('');
}
if(ret.message.indexOf("Priceinvalid")>=0){
$('#price-error').css('display', 'block');
$('#price-error').html('Price accepts only neumerical digits');
}else{
$('#price-error').html('');
}
}else{
$('#purpose-error').html('');
$('#type-error').html('');
$('#stories-error').html('');
$('#bedrooms-error').html('');
$('#bathrooms-error').html('');
$('#divs_states-error').html('');
$('#township-error').html('');
$('#price-error').html('');
}
},
error: function(){
// the AJAX request failed as in timed out / bad url etc.
}
});
}
$( "#submitbutton" ).on( "click", validatelanded );
function validatelanded( event ){
if (!$("input[name='purpose']:checked").val()) {
$('#purpose-error').css('display', 'block');
$('#purpose-error').html('Please select to Sell or to Rent');
return false;
}else{
$('#purpose-error').html('');
}
if (!$("input[name='type']:checked").val()) {
$('#type-error').css('display', 'block');
$('#type-error').html('Please select one of the Building types');
return false;
}else{
$('#type-error').html('');
}
if($("input[name='type']:checked").val() == "With_RC" || $("input[name='type']:checked").val() == "With_BrickNorcal"){
if($( "#stories" ).val() == "Stories"){
$('#stories-error').css('display', 'block');
$('#stories-error').html('Please select number of stories at the building');
return false;
}else{
$('#stories-error').html('');
}
if($( "#bedrooms" ).val() == "Bedrooms"){
$('#bedrooms-error').css('display', 'block');
$('#bedrooms-error').html('Please select number of bedrooms at the building');
return false;
}else{
$('#bedrooms-error').html('');
}
if($( "#bathrooms" ).val() == "Bathrooms"){
$('#bathrooms-error').css('display', 'block');
$('#bathrooms-error').html('Please select number of bathrooms at the building');
return false;
}else{
$('#bathrooms-error').html('');
}
}
if($( "#divs_states" ).val() == "Division" || $( "#divs_states" ).val() == "State"){
$('#divs_states-error').css('display', 'block');
$('#divs_states-error').html('Please select a Division or a State');
return false;
}else{
$('#divs_states-error').html('');
}
if($( "#township" ).val() == "Township" ){
$('#township-error').css('display', 'block');
$('#township-error').html('Please select a township');
return false;
}else{
$('#township-error').html('');
}
var price = $('#price').val();
if ($.trim(price) == '' ) {
$('#price-error').css('display', 'block');
$('#price-error').html('Please include price');
return false;
}else if(!price.match(/^\d+$/)){
$('#price-error').css('display', 'block');
$('#price-error').html('Price can include only numerical digits');
return false;
}else{
$('#price-error').html('');
}
var length = $('#length').val();
if ($.trim(length) == '' ) {
$('#length-error').css('display', 'block');
$('#length-error').html('Please include length of the land');
return false;
}else if(!length.match(/^\d+$/)){
$('#length-error').css('display', 'block');
$('#length-error').html('Please include length in correct format');
return false;
}else{
$('#length-error').html('');
}
var width = $('#width').val();
if ($.trim(width) == '' ) {
$('#width-error').css('display', 'block');
$('#width-error').html('Please include width of the land');
return false;
}else if(!width.match(/^\d+$/)){
$('#width-error').css('display', 'block');
$('#width-error').html('Please include width in correct format');
return false;
}else{
$('#width-error').html('');
}
if (!$("input[name='haveaircon']:checked").val()) {
$('#haveaircon-error').css('display', 'block');
$('#haveaircon-error').html('Please select for the aircon');
return false;
}else{
$('#haveaircon-error').html('');
}
if($( "#possession" ).val() == "Possession"){
$('#possession-error').css('display', 'block');
$('#possession-error').html('Please select possession type');
return false;
}else{
$('#possession-error').html('');
}
if ($.trim($('#date').val()) == '' ) {
$('#date-error').css('display', 'block');
$('#date-error').html('Please include available date for start use');
return false;
}else{
$('#date-error').html('');
}
if ($('#textarea').val() == "" || $('#textarea').val() =="Please enter additional information here...")
{
$('#textarea-error').css('display', 'block');
$('#textarea-error').html('Please enter additional information in the above text area...');
return false;
}else{
$('#textarea-error').html('');
}
if (!$("input[name='agentowner']:checked").val()) {
$('#agentowner-error').css('display', 'block');
$('#agentowner-error').html('Please select Agent or Owner');
return false;
}else{
$('#agentowner-error').html('');
}
var name = $('#name').val();
if( $.trim(name) == '' ){
$('#name-error').css('display', 'block');
$('#name-error').html('Please include name of the person who submit this advertisement.');
return false;
}else{
$('#name-error').html('');
}
var phone= $('#phone').val();
if ($.trim(phone) == '') {
$('#phone-error').css('display', 'block');
$('#phone-error').html('Please include phone number to contact.');
return false;
} else if(phone.length < 6){
$('#phone-error').css('display', 'block');
$('#phone-error').html('Please include valid phone number to contact.');
return false;
}else if (!phone.match(/^[0-9]+$/)){
$('#phone-error').css('display', 'block');
$('#phone-error').html('Please include valid phone number to contact.');
return false;
}else{
$('#phone-error').html('');
}
var email= $('#email').val();
if ($.trim(email) == '') {
$('#email-error').css('display', 'block');
$('#email-error').html('Please include email number to contact.');
return false;
}else if (!email.match(/^[-a-z0-9~!$%^&*_=+}{\'?]+(\.[-a-z0-9~!$%^&*_=+}{\'?]+)*#([a-z0-9_][-a-z0-9_]*(\.[-a-z0-9_]+)*\.(aero|arpa|biz|com|coop|edu|gov|info|int|mil|museum|name|net|org|pro|travel|mobi|[a-z][a-z])|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(:[0-9]{1,5})?$/i)) {
$('#email-error').css('display', 'block');
$('#email-error').html('Please include valid email number to contact.');
return false;
}else{
$('#email-error').html('');
}
sendtoServer();
}
</script>
</html>
When I work with multiple forms I give each opening <form> tag a unique id and serialize data on that specific id. Your form in your edit has the 'advertiseForm' id, not 'form'. Don't forget the # character when writing ids in js.
Your js should look like this: $("#advertiseForm").serialize(), this will serialize the form with the id 'advertiseForm'. The other form must also have a unique id or class name in order to serialize it properly.

Execute function with value of current selected option

Even if i have selected an options it still alert a message "Please choose something."
I got this working with only one dropdown list, but i have problems when there are two or more.
(In working example variable sport is document.getElementById("sports") and only one dropdown list)
What's the issue?
<script type="text/javascript">
function check() {
sport = document.getElementsByClassName("sports");
sport_selected = sport.selectedIndex;
weight = document.getElementById("weight").value;
time = document.getElementById("time").value;
if (sport_selected > 0) {
if (isNaN(weight, time)) {
alert("Error. This is not a number.");
}
else {
met = sport.options[sport_selected].value;
calculations = (time * ((met * 3.5 * weight)/200));
result = Math.round(calculations);
document.lastform.output.value = result + " kcal";
}
}
else {
alert("Please choose something.")
}
});
</script>
<div id="tabs">
<ul>
<li>Running</li>
<li>Walking</li>
</ul>
<div id="tabs-1">
<form name="form1">
<select class="sports">
<option value="">-Choose-</option>
<option value="6">Jog/walk combination</option>
<option value="7">Jogging, general</option>
<option value="8">Running, 5 mph (12 min/miile)</option>
<option value="9">Running, 5.2 mph (11.5 min/mile)</option>
<option value="10">Running, 6 mph (10 min/mile)</option>
</select>
</form>
</div>
<div id="tabs-2">
<form name="form2">
<select class="sports">
<option value="">-Choose-</option>
<option value="2">Walking, general</option>
<option value="2">Walking, 1 mph</option>
</select>
</form>
</div>
</div>
<form name="lastform">
<label for="weight">Weight [kg]:</label><br />
<input type="text" size="3" id="weight"><br />
<label for="time">Duration [min]:</label><br />
<input type="text" size="3" id="time">
<input type="button" value="Calc" onClick="check()"><br /><br />
<label for="kcal">You have burned:</label><br />
<input type="text" id="output">
</form>
getElementsByClassName is returning a collection but not just one item, you need to write code to iterate the collection if you have more controls. please check: https://developer.mozilla.org/en/DOM/document.getElementsByClassName
What about using jQuery, since you've used the TAG ?
HTML
<div id="tabs">
<ul>
<li>Running</li>
<li>Walking</li>
</ul>
<div id="tabs-1">
<form name="form1">
<select class="sports">
<option value="">-Choose-</option>
<option value="6">Jog/walk combination</option>
<option value="7">Jogging, general</option>
<option value="8">Running, 5 mph (12 min/miile)</option>
<option value="9">Running, 5.2 mph (11.5 min/mile)</option>
<option value="10">Running, 6 mph (10 min/mile)</option>
</select>
</form>
</div>
<div id="tabs-2">
<form name="form2">
<select class="sports">
<option value="">-Choose-</option>
<option value="2">Walking, general</option>
<option value="2">Walking, 1 mph</option>
</select>
</form>
</div>
</div>
<form name="lastform">
<label for="weight">Weight [kg]:</label><br />
<input type="text" size="3" id="weight"><br />
<label for="time">Duration [min]:</label><br />
<input type="text" size="3" id="time">
<input type="button" value="Calc" id="check"><br /><br />
<label for="kcal">You have burned:</label><br />
<input id="result" type="text" id="output">
</form>
javascript
$("#check").click(function() {
var sport_selected = $(".sports option:selected").val();
var weight = $("#weight").val();
time = $("#time").val();
if (parseInt(sport_selected) > 0) {
if (isNaN(weight, time)) {
alert("Error. This is not a number.");
}
else {
var met = sport_selected
calculations = (time * ((met * 3.5 * weight) / 200));
result = Math.round(calculations);
$("#result").val(result + " kcal");
}
}
else {
alert("Please choose something.")
}
});​
and this is the fiddle.

Radio button Values not Parsed

I am building a point calculation system that calculates points based on input value.
I've used some jquery ui styling on this radio button and now it doesnt add up, in the total.
Code is too long to post here so check this live preview. i read through code a lot of times cou;ldnt find anything.
EDIT: here's a stripped down version of my code:
the problem is with the radio buttons in div part2, please read my comments.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Quebec and Federal Immigration Points Calculator</title>
<link rel="stylesheet" href="files/jquery00.css">
<link rel="stylesheet" href="files/flexselect.css">
<link rel="stylesheet" href="files/demos000.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js" type="text/javascript"></script>
<script src="files/liquidmetal.js"></script>
<script src="files/jquery.flexselect.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("select.flexselect").flexselect();
$( ".radio" ).buttonset();//here they are made into jquery ui buttonsets
$('#part1').show('slow', function() {
});
});
</script>
<script type="text/javascript">
function showAge(){
var d =document.getElementById('dob').value.split('/');
var today = new Date();
var bday = new Date(d[2],d[1],d[0]);
var age = today.getFullYear() - bday.getFullYear();
if(today.getMonth() < bday.getMonth() || (today.getMonth() == bday.getMonth() && today.getDate() < bday.getDate()))
{
t = age-1;
}
else {
t = age
}
document.getElementById('form').age.value = t;
}
</script>
<script type="text/javascript">
function compute(form)
{
var a = parseInt(document.getElementById('form').age.value, 10) || 0;
if ((18 <= a) && (a <= 35)){
q = 16;
}
else if (a == 36){
q = 14;
}
else if (a == 37){
q = 12;
}
else if (a == 38){
q = 10;
}
else if (a == 39){
q = 8;
}
else if (a == 40){
q = 6;
}
else if (a == 41){
q = 4;
}
else if (a == 42){
q = 2;
}
else if ((18 > a) || (a > 43)){
q = 0;
}
var b = parseInt(document.getElementById('form').highed.value, 10) || 0;
if (b == 1){
c = 0;
}
else if (b == 2){
c = 2;
}
else if (b == 3){
c = 4;
}
else if (b == 4){
c = 6;
}
var aos = parseInt(document.getElementById('form').selectareaofstudy.value, 10) || 0;
//here the value of the radiio button is parsed, and if nothing is selected it will default to zero
var tcfc2 = parseInt(document.getElementById('form').TCFC2.value, 10) || 0;
qt = (aos + c + q + tcfc2);
document.getElementById('total').age.value = q;
document.getElementById('total').ed.value = c;
document.getElementById('total').aos.value = aos;
document.getElementById('total').tcfc2.value = tcfc2;//here the value is displayed
document.getElementById('total').total.value = qt;//total displayed here
}
</script>
<script type="text/javascript">
function show2() {
$('#part1').hide('fast');
$('#part2').show('slow');
}
function back2() {
$('#part1').show('slow');
$('#part2').hide('fast');
}
function showTCF() {
if($('#radio1-1').is(':checked')) { alert("it's checked"); }
}
</script>
</head>
<body>
<div id="formbox">
<form id="form" name="form">
<div id="part1" style="display:none">
<div id="hidden">
<p>Your Date of Birth (format:<strong>dd/mm/yyyy</strong>)</p>
<br />
<input onBlur="compute(this.form)" onchange="showAge()" name="dob" id="dob" />
</div>
<p>Your Age</p>
<input class="sev" name="age" type="text" onMouseOver="compute(this.form)" style="font-size: 15px" value="" size="7" />
<h1>Your education</h1>
<h2>Your highest level of Education:</h2>
<select onchange="compute(this.form)" name="highed">
<option value="">Select One</option>
<option value="1">No high school diploma or general Professional</option>
<option value="2">High school general diploma +2 or 12th grade</option>
<option value="3">Postsecondary diploma 2 years general of full-time studies</option>
<option value="4">Postsecondary technical diploma 1 year of full-time studies</option>
<option value="4">Postsecondary technical diploma 2 years of full-time studies</option>
</select>
<h2>Your Area of Education:<small>(start typing..)</small></h2>
<select class="flexselect" name="selectareaofstudy">
<option value=""></option>
<option value="6">3D Animation and Image Synthesis Techniques (DCS - 3 years) </option>
<option value="6">LOADS OF OTHER VALUES HERE</option>
</select>
<br />
<br />
<INPUT class="ten" NAME="calc" VALUE="Calculate" TYPE="button" onClick="compute(this.form)">
<INPUT class="ten" NAME="calc" VALUE="Next" TYPE="button" onClick="show2()">
<br />
</div>
<div id="part2" style="display:none">
<h2>French Proficiency</h2>
<p>Have you written: <strong>TCF Quebec/ TEFaQ/ TCF/ TEF level C2- DALF C2?</strong> </p>
<div id="radio1" class="radio">
<!--These radio buttons have values of 1 and 2 but when calculated they always show up as zero, the default values.-->
<input id="radio1-1" name="TCFC2" type="radio" value="1" checked="checked" />
<label for="radio1-1">Yes</label>
<input id="radio1-2" name="TCFC2" type="radio" value="2" />
<label for="radio1-2">No</label>
</div>
<br />
<br />
<br />
<INPUT class="ten" NAME="calc" VALUE="Calculate" TYPE="button" onClick="compute(this.form)">
<table>
<tr>
<td><INPUT class="ten" NAME="calc" VALUE="Back" TYPE="button" onClick="back2()"></td>
<td><INPUT class="ten" NAME="calc" VALUE="Next" TYPE="button" onClick="show3()"></td>
</tr>
</table>
</div>
</form>
</div>
<div style="" id="totalmenu" class="port-menu-wrapper">
<form id="total">
<h3>Points For</h3>
<table>
<tr>
<td><label>Age</label></td>
<td><input class="sev" name="age" type="text" style="font-size: 15px" value="" size="7" readonly></td>
</tr>
<tr>
<td><label style="font-size: 18px">Your Education</label></td>
</tr>
<tr>
<td><label>Education 1</label></td>
<td><input class="sev" name="ed" type="text" style="font-size: 15px" value="" size="7" readonly></td>
</tr>
<tr>
<td><label>Area of Study</label></td>
<td><input class="sev" name="aos" type="text" style="font-size: 15px" value="" size="7" readonly></td>
</tr>
<tr>
<td><label style="font-size: 18px">French Proficiency</label></td>
</tr>
<tr>
<td><label>TCFC2</label></td>
<td><input class="sev" name="tcfc2" type="text" style="font-size: 15px" value="" size="7" readonly></td>
</tr>
<tr>
<td><label style="font-size:20px;"><strong>Total</strong></label></td>
<td><input class="ten" name="total" type="text" style="font-size: 20px" value="" size="10" readonly></td>
</tr>
</table>
</form>
</div>
</body>
</html>
i don't think it's linked to jquery ui, but to the line
var tcfc2 = parseInt(document.getElementById('form').TCFC2.value, 10) || 0;
as you have 2 elements with radio buttons called TCFC2, an array is created with them. Moreover, the the value is always 1 for the first radio, and 2 for the second. You need to check the "checked" property, not the value to identify if people speak french.
var tcfc2 = document.getElementById('form').TCFC2[0].checked -0 ;
No parseInt, as "true" or "false" are returned, the "-0" is to force the int conversion.
Finally, I would rename the radios OR the input type text to something else than TCFC2. (and merge your css, get the scripts and styles out the html file and into their own files for maintenance stake, and name your vars to something more meaningful than a, b, and c...)

Categories

Resources