Submit button clears form instead of opening div - javascript

I'm trying to open another div that displays what the user entered in the form onsubmit, but the submit button just clears the form, and I can't figure out why. We have to use Javascript to display the results. Here's the code:
<!DOCTYPE html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<style>
h1 {
text-align: center;
color: blue;
font-family: 'Courier';
margin: 30px;
}
h2 {
margin-top: 40px;
margin-left: 500px;
margin-bottom: 20px;
}
#divresults {
display: none;
}
</style>
</head>
<body>
<div id="customerform">
<form onsubmit="return showResults();">
<p>First Name: <input type="text" id="fname" value="" required /></p>
<p>Last Name: <input type="text" id="lname" value="" required /></p>
<p>Street Address: <input type="text" id="address" value="" required /></p>
<p>City: <input type="text" id="city" value="" required /></p>
<p>State:
<select id="states" required>
<option id="statedefault" value="">Please select your state</option>
<option value="Alabama">Alabama</option>
<option value="Alaska">Alaska</option>
<option value="Arizona">Arizona</option>
<option value="Arkansas">Arkansas</option>
<option value="California">California</option>
<option value="Colorado">Colorado</option>
<option value="Connecticut">Connecticut</option>
<option value="Delaware">Delaware</option>
<option value="Florida">Florida</option>
<option value="Georgia">Georgia</option>
<option value="Hawaii">Hawaii</option>
<option value="Idaho">Idaho</option>
<option value="Illinois">Illinois</option>
<option value="Indiana">Indiana</option>
<option value="Iowa">Iowa</option>
<option value="Kansas">Kansas</option>
<option value="Kentucky">Kentucky</option>
<option value="Louisiana">Louisiana</option>
<option value="Maine">Maine</option>
<option value="Maryland">Maryland</option>
<option value="Massachusetts">Massachusetts</option>
<option value="Michigan">Michigan</option>
<option value="Minnesota">Minnesota</option>
<option value="Mississippi">Mississippi</option>
<option value="Missouri">Missouri</option>
<option value="Montana">Montana</option>
<option value="Nebraska">Nebraska</option>
<option value="Nevada">Nevada</option>
<option value="New Hampshire">New Hampshire</option>
<option value="New Jersey">New Jersey</option>
<option value="New Mexico">New Mexico</option>
<option value="New York">New York</option>
<option value="North Carolina">North Carolina</option>
<option value="North Dakota">North Dakota</option>
<option value="Ohio">Ohio</option>
<option value="Oklahoma">Oklahoma</option>
<option value="Oregon">Oregon</option>
<option value="Pennsylvania">Pennsylvania</option>
<option value="Rhode Island">Rhode Island</option>
<option value="South Carolina">South Carolina</option>
<option value="South Dakota">South Dakota</option>
<option value="Tennessee">Tennessee</option>
<option value="Texas">Texas</option>
<option value="Utah">Utah</option>
<option value="Vermont">Vermont</option>
<option value="Virginia">Virginia</option>
<option value="Washington">Washington</option>
<option value="West Virginia">West Virginia</option>
<option value="Wisconsin">Wisconsin</option>
<option value="Wyoming">Wyoming</option>
</select>
</p>
<p>Zip Code: <input type="text" id="zip" required /></p>
<p>Gender:
<input type="radio" name="sex" value="male" checked />Male
<input type="radio" name="sex" value="female" />Female
</p>
<input type="submit" id="submitbutton" />
<input type="reset" id="clear" value="Clear" />
</form>
</div>
<br/>
<div id="divresults">
<h2>You entered: </h2>
<p>First Name: <span id="first" class="results"></span></p>
<p>Last Name: <span id="last" class="results"></span></p>
<p>Street Address: <span id="street" class="results"></span></p>
<p>City: <span id="cityresult" class="results"></span></p>
<p>State: <span id="stateresult" class="results"></span></p>
<p>Zip: <span id="zipcode" class="results"></span></p>
<p>Gender: <span id="gen" class="results"></span></p>
<input type="button" id="formreset" value="Go Back to Form" onclick="resetForm();" />
</div>
<script>
function showResults() {
//store form values
var fst = document.getElementById("fname").value;
var lst = document.getElementById("lname").value;
var st = document.getElementById("address").value;
var cty = document.getElementById("city").value;
var ste = document.getElementById("states").value;
var zp = document.getElementById("zip").value;
var gndr = "male";
var genders = document.getElementsByName("sex");
for (var i = 0; i < 2; i++) {
if (genders[i].checked) {
gndr = radios[i].value;
break;
}
}
clearForm();
//switch divs
document.getElementById("customerform").style.display = "none";
document.getElementById("divresults").style.display = "block";
//display results
document.getElementById("first").innerHTML = fst;
document.getElementById("last").innerHTML = lst;
document.getElementById("street").innerHTML = st;
document.getElementById("cityresult").innerHTML = cty;
document.getElementById("stateresult").innerHTML = ste;
document.getElementById("zipcode").innerHTML = zp;
document.getElementById("gen").innerHTML = gndr;
return false;
}
function clearForm() {
document.getElementById("fname").value = "";
document.getElementById("lname").value = "";
document.getElementById("address").value = "";
document.getElementById("city").value = "";
document.getElementById("states").value = "";
document.getElementById("zip").value = "";
}
function resetForm() {
document.getElementById("first").innerHTML = "";
document.getElementById("last").innerHTML = "";
document.getElementById("street").innerHTML = "";
document.getElementById("cityresult").innerHTML = "";
document.getElementById("stateresult").innerHTML = "";
document.getElementById("zipcode").innerHTML = "";
document.getElementById("gen").innerHTML = "";
document.getElementById("customerform").style.display = "block";
document.getElementById("divresults").style.display = "none";
}
</script>
</body>
</html>

You have an error Uncaught ReferenceError: radios is not defined, in the for loop you are using radios[i].value which should be genders[i].value
for (var i = 0; i < 2; i++) {
if (genders[i].checked) {
gndr = genders[i].value;
break;
}
}
Demo: Fiddle

Related

get and store values from many selects at same time

I got 7 select that I need to read their value to use it later on, but I can only read the value of the firts select, if I tried to read a second one or more, it crashes.
I need to be able to identify which selects' value is different from "" to read it, but if the value is equal to "", then ignore it.
This is my script:
$(document).ready(function() {
$("#MENU").change(function() {
$(this).find("option:selected").each(function() {
var optionValue = $(this).attr("value");
if (optionValue) {
$(".box").not("." + optionValue).hide();
$("." + optionValue).show();
} else {
$(".box").hide();
}
});
}).change();
});
function myFuction() {
//Getting Value
//var selValue = document.getElementById("singleSelectDD").value;
var selObj = document.getElementById("MENU");
var selValue = selObj.options[selObj.selectedIndex].value;
//Setting Value
document.getElementById("valorsel").value = selValue;
}
function ELEMENTO() {
//Getting Value
//var selValue = document.getElementById("singleSelectDD").value;
var modifica1 = document.getElementById("AREA");
var modifica2 = document.getElementById("BANCO");
var modifica3 = document.getElementById("USOCFDI");
var modifica4 = document.getElementById("DEPARTAMENTO");
var modifica5 = document.getElementById("EMPRESA");
var modifica6 = document.getElementById("GIRO");
var modifica7 = document.getElementById("NEGOCIO");
var modval1 = modifica1.options[modifica1.selectedIndex].value;
var modval2 = modifica2.option[modifica2.selectedIndex].value;
var modval3 = modifica3.option[modifica3.selectedIndex].value;
var modval4 = modifica4.option[modifica4.selectedIndex].value;
var modval5 = modifica5.option[modifica5.selectedIndex].value;
var modval6 = modifica6.option[modifica6.selectedIndex].value;
var modval7 = modifica7.option[modifica7.selectedIndex].value;
}
document.getElementById("Actualiza").addEventListener("click", function Act() {
var res = document.getElementById("modfinal").value;
document.getElementById("IDDATO").innerHTML = res;
var txt = document.getElementById("valorsel").value;
document.getElementById("RESULTADO").innerHTML = txt;
var txt2 = document.getElementById("GLOBAL").value;
document.getElementById("GLOB").innerHTML = txt2;
});
document.getElementById("submit").addEventListener("click", function Act() {
var res = document.getElementById("modfinal").value;
document.getElementById("IDDATO").innerHTML = res;
var txt = document.getElementById("valorsel").value;
document.getElementById("RESULTADO").innerHTML = txt;
var txt2 = document.getElementById("GLOBAL").value;
document.getElementById("GLOB").innerHTML = txt2;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<form name="CXP" action="Guarda_CXP2.php" method="post" target="_blank">
<h1 style="text-align: center"> Cuentas por Pagar </h1>
<p>Seleccione una opciĆ³n</p>
<div>
<select name="MENU" id="MENU" onchange="myFuction()">
<option value="" selected></option>
<option value="1">Area</option>
<option value="2">Bancos</option>
<option value="3">CFDI</option>
<option value="4">Departamentos</option>
<option value="5">Empresa</option>
<option value="6">Giro Comercial</option>
<option value="7">Negocio</option>
</select><br><br>
<p>Texto Global</p>
<input type="text" name="GLOBAL" id="GLOBAL" value="" placeholder="Texto global">
</div>
<div class="1 box">
<p>Seleccione el Area deseada</p>
<select name="AREA" id="AREA" class="HIJOS" onclick="ELEMENTO()">
<option value="" selected></option>
<option value="1">AREA 1</option>
<option value="2">AREA 2</option>
<option value="3">AREA 3 </option>
</select>
</div>
<div class="2 box">
<p>Selecione el Banco deseado</p>
<select name="BANCO" id="BANCO" class="HIJOS" onchange="ELEMENTO()">
<option value="" selected></option>
<option value="1">BANCO 1</option>
<option value="2">BANCO 2</option>
<option value="3">BANCO 3</option>
</select>
</div>
<div class="3 box">
<p> Ingrese el uso de CFDI</p>
<select name="USOCFDI" id="USOCFDI" class="HIJOS" onchange="ELEMENTO()">
<option value="" selected></option>
<option value="1">CFDI 01</option>
<option value="2">CFDI 02</option>
<option value="3">CFDI 03</option>
</select>
</div>
<div class="4 box">
<p> Seleccione el Deparmaneto deseado </p>
<select name="DEPARTAMENTO" id="DEPARTAMENTO" class="HIJOS" onchange="ELEMENTO()">
<option value="" selected></option>
<option value="1">DEPARTAMENTO 1</option>
<option value="2">DEPARTAMENTO 2</option>
<option value="3">DEPARTAMENTO 3</option>
</select>
</div>
<div class="5 box">
<p> Seleccione la Empresa deseada</p>
<select name="EMPRESA" id="EMPRESA" class="HIJOS" onchange="ELEMENTO()">
<option value="" selected></option>
<option value="1">EMPRESA 1</option>
<option value="2">EMPRESA 2</option>
<option value="3">EMPRESA 3</option>
</select>
</div>
<div class="6 box">
<p> Seleccione el Giro Comercial</p>
<select name="GIRO" id="GIRO" class="HIJOS" onchange="ELEMENTO()">
<option value="" selected></option>
<option value="1">GIRO 1</option>
<option value="2">GIRO 2</option>
<option value="3">GIRO 3</option>
</select>
</div>
<div class="7 box">
<p> Ingrese el tipo de Negocio</p>
<select name="NEGOCIO" id="NEGOCIO" class="HIJOS" onchange="ELEMENTO()">
<option value="" selected></option>
<option value="1">NEGOCIO 1</option>
<option value="2">NEGOCIO 2</option>
<option value="3">NEGOCIO 3</option>
</select>
</div><br>
<div>
<input type="button" value="button" name="button">
<input type="submit" id="Actualiza" value="Actualizar" name="Actualizar" onclick="Act">
<input type="submit" id="submit" value="Agregar" name="Agregar">
</div>
<input type="text" name="valorsel" id="valorsel" class="form-control" placeholder="ID para tabla">
<input type="text" name="modfinal" id="modfinal" class="form-control" placeholder="ID para dato">
<p name="RESULTADO" id="RESULTADO"></p>
<p name="IDDATO" id="IDDATO"></p>
<p name="GLOB" id="GLOB"></p>
</form>
This is some text box I use to be able to watch if it is working:
<input type="text" name="modfinal" id="modfinal" class="form-control" placeholder="ID para dato">
https://jsfiddle.net/Ulises9663/x2z3bjyo/
Look, there's much code on your example and I don't know exactly what is the desired output and objective, but one thing I can suggest you to do to be much easier is:
Create a global variable, let's call it objSelecteds.
ELEMENTO() function can be shortened, no need to get every element every time it is called, in the HTML, pass this as parameter, then inside the function the parameter can be used to access the element directly.
With that, now use the <select> element id as key and the value of the selected option as value to insert into our objSelecteds.
That way, each select that got modiefied will have it's id and selected value saved inside objSelecteds.
Now, when you need to check the selected values, you only need to access the objSelecteds and see each value for each select.
Take a look at the code below, run the snippet and made some changes to the selects, see if you understand it and if it helps you:
let objSelecteds = {}
function ELEMENTO(self) {
let modval = self.options[self.selectedIndex].value;
objSelecteds[self.id] = modval;
console.clear()
console.log(objSelecteds)
}
function checkSelections(){
let validSelections = []
for (let key in objSelecteds){
let selectValue = objSelecteds[key]
if (key != "" && key != null){
validSelections.push(key)
}
}
console.clear()
console.log("Those selections are valid and have some value:", validSelections)
return validSelections
}
<button onclick="checkSelections()">Check selections</button>
<div class="1 box">
<p>Seleccione el Area deseada</p>
<select name="AREA" id="AREA" class="HIJOS" onclick="ELEMENTO(this)">
<option value="" selected></option>
<option value="1">AREA 1</option>
<option value="2">AREA 2</option>
<option value="3">AREA 3 </option>
</select>
</div>
<div class="2 box">
<p>Selecione el Banco deseado</p>
<select name="BANCO" id="BANCO" class="HIJOS" onchange="ELEMENTO(this)">
<option value="" selected></option>
<option value="1">BANCO 1</option>
<option value="2">BANCO 2</option>
<option value="3">BANCO 3</option>
</select>
</div>
<div class="3 box">
<p> Ingrese el uso de CFDI</p>
<select name="USOCFDI" id="USOCFDI" class="HIJOS" onchange="ELEMENTO(this)">
<option value="" selected></option>
<option value="1">CFDI 01</option>
<option value="2">CFDI 02</option>
<option value="3">CFDI 03</option>
</select>
</div>
<div class="4 box">
<p> Seleccione el Deparmaneto deseado </p>
<select name="DEPARTAMENTO" id="DEPARTAMENTO" class="HIJOS" onchange="ELEMENTO(this)">
<option value="" selected></option>
<option value="1">DEPARTAMENTO 1</option>
<option value="2">DEPARTAMENTO 2</option>
<option value="3">DEPARTAMENTO 3</option>
</select>
</div>
<div class="5 box">
<p> Seleccione la Empresa deseada</p>
<select name="EMPRESA" id="EMPRESA" class="HIJOS" onchange="ELEMENTO(this)">
<option value="" selected></option>
<option value="1">EMPRESA 1</option>
<option value="2">EMPRESA 2</option>
<option value="3">EMPRESA 3</option>
</select>
</div>
<div class="6 box">
<p> Seleccione el Giro Comercial</p>
<select name="GIRO" id="GIRO" class="HIJOS" onchange="ELEMENTO(this)">
<option value="" selected></option>
<option value="1">GIRO 1</option>
<option value="2">GIRO 2</option>
<option value="3">GIRO 3</option>
</select>
</div>
<div class="7 box">
<p> Ingrese el tipo de Negocio</p>
<select name="NEGOCIO" id="NEGOCIO" class="HIJOS" onchange="ELEMENTO(this)">
<option value="" selected></option>
<option value="1">NEGOCIO 1</option>
<option value="2">NEGOCIO 2</option>
<option value="3">NEGOCIO 3</option>
</select>
</div><br>
<div>
You can use an if statement to see if it is empty or not. See the example below:
function ELEMENTO(){
var modifica1 = document.getElementById("BANCO");
var modval1= modifica1.options[modifica1.selectedIndex].value;
var val = modval1.trim();
if(val){
document.getElementById("modfinal").value = modval1;
}
}
Hope this helps!

cloning jquery button twice and having both of them working doing the same task

i have a button that i wish to clone in jquery so that i can have two of them, using both buttons to do the same task however when i run this code only one of the buttons actually works and the other does not.
I have looked it up trying to use true as a parameter and it still doesnt work
any help would be much appreciated
jQuery(function($) {
var $button = $('#addEvent'),
$row = $('.newEvent').clone();
$button.click(function() {
$row.clone().insertBefore($button);
});
});
jQuery(function($) {
var $button = $('#newPupil'),
$row = $('.newParticipant').clone();
$button.click(function() {
$row.clone().insertBefore($button);
});
});
<form>
<div class="newEvent">
<fieldset id="ResultSheet">
<legend>Add Event</legend>
Event: <br>
<select name="Events" id="Events">
<option disabled selected value> --SELECT AN OPTION BELOW-- </option>
<option value="100 Metres">100 Metres</option>
<option value="200 Metres">200 Metres</option>
<option value="300 Metres">300 Metres</option>
<option value="400 Metres">400 Metres</option>
<option value="800 Metres">800 Metres</option>
<option value="1500 Metres">1500 Metres</option>
<option value="400 Metres">400 Metres</option>
<option value="Hurdels">Hurdels</option>
<option value="Shot Put">Shot Put</option>
<option value="Discus">Discus</option>
<option value="Javelin">Javelin</option>
<option value="Long Jump">Long Jump</option>
<option value="High Jump">High Jump</option>
<option value="Triple Jump">Triple Jump</option>
<option value="4x100 Metres Relay">4x100 Metres relay</option>
</select>
<div class="newParticipant">
<br> First name: <input type="text" name="fisrtName"> Last Name: <input type="text" name="lastName">
</div>
<input type="button" id="newPupil" name="newPupil" value="New participant">
</fieldset>
</div>
</form>
<input type="button" id="addEvent" name="addEvent" value="Add Event" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
Attribute id must be unique in a document, use class instead. To attach dynamically created element use on().
Try the following way:
jQuery(function($){
var $button1 = $('#addEvent'),
$row1 = $('.newEvent').clone();
$button1.click(function(){
$row1.clone().insertBefore($button1);
});
var $row2 = $('.newParticipant').clone();
$('body').on('click', '.newPupil', function(){
$row2.clone().insertBefore(this);
});
});
<div class="newEvent">
<fieldset id="ResultSheet">
<legend>Add Event</legend>
Event: <br>
<select name="Events" id="Events">
<option disabled selected value> --SELECT AN OPTION BELOW-- </option>
<option value="100 Metres">100 Metres</option>
<option value="200 Metres">200 Metres</option>
<option value="300 Metres">300 Metres</option>
<option value="400 Metres">400 Metres</option>
<option value="800 Metres">800 Metres</option>
<option value="1500 Metres">1500 Metres</option>
<option value="400 Metres">400 Metres</option>
<option value="Hurdels">Hurdels</option>
<option value="Shot Put">Shot Put</option>
<option value="Discus">Discus</option>
<option value="Javelin">Javelin</option>
<option value="Long Jump">Long Jump</option>
<option value="High Jump">High Jump</option>
<option value="Triple Jump">Triple Jump</option>
<option value="4x100 Metres Relay">4x100 Metres relay</option>
</select>
<div class="newParticipant">
<br>
First name: <input type="text" name="fisrtName">
Last Name: <input type="text" name="lastName">
</div>
<input type="button" class="newPupil" name="newPupil" value="New participant">
</fieldset>
</div>
<input type="button" id="addEvent" name="addEvent" value="Add Event" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<button value="Refresh Page" onClick="refreshPage()">REFRESH</button>
<script src="newButtons.js"></script>

How can I do calculations using Jquery and output them in html?

I want to calculate percentage using javascript.
If the selected value in place1 & place2 is not equal then the calculation should be displayed in both flvalue & flvalues.
Ex: If value is 1000 and selected percent is 10 and selected place1 & place2 value is equal then flvalue should be 1100.
If value is 1000 and selected percent is 10 and selected place1 & place2 value is notequal then flvalue should be 1100 and flvalues should be 1100.
<script>
$('#percent,#input,#place,#places').on('change input', function() {
var val = Number($('#input').val()) || 0,
per = Number($('#percent').val()) || 0;
if($('#place').val()!=$('#places')){
$('#total').val(val + val * per / 100)
$('#totals').val(val + val * per / 100)
})
</script>
Value
<input type="text" name="gvalue" id="input" class="input" required/>Percentage
<select name="percent" id="percent" class="input">
<option value="Country" selected>Select Percentage</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
</select>
Place_1
<select name="place_1" id="place_1" class="input">
<option value="Place" selected>Place</option>
<option value="Place 1">Place 1</option>
<option value="Place 2">Place 2</option>
<option value="Place 3">Place 3</option>
</select>
Place_2
<select name="place_2" id="place_2" class="input">
<option value="Place" selected>Place</option>
<option value="Place 1">Place 1</option>
<option value="Place 2">Place 2</option>
<option value="Place 3">Place 3</option>
</select>
Final Value
<input type="text" name="flvalue" class="input" id="total" required/>
<input type="text" name="flvalues" class="input" id="totals" required/>
Give it a try to this,
$('#percent,#input,#place_2,#place_1').on('change input', function() {
var val = Number($('#input').val()) || 0,
per = Number($('#percent').val()) || 0;
var tot_am = val + val * per / 100;
if ($('#place_1').val() != $('#place_2').val()) {
$('#total').val(tot_am);
$('#totals').val(tot_am);
} else if ($('#place_1').val() == $('#place_2').val()) {
$('#total').val()
$('#totals').val('');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Value
<input type="text" name="gvalue" id="input" class="input" required/>Percentage
<select name="percent" id="percent" class="input">
<option value="Country" selected>Select Percentage</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
</select>
Place_1
<select name="place_1" id="place_1" class="input">
<option value="Place" selected>Place</option>
<option value="Place 1">Place 1</option>
<option value="Place 2">Place 2</option>
<option value="Place 3">Place 3</option>
</select>
Place_2
<select name="place_2" id="place_2" class="input">
<option value="Place" selected>Place</option>
<option value="Place 1">Place 1</option>
<option value="Place 2">Place 2</option>
<option value="Place 3">Place 3</option>
</select>
Final Value
<input type="text" name="flvalue" class="input" id="total" required/>
<input type="text" name="flvalues" class="input" id="totals" required/>
Hope this will solve your problem.
You've just to add condition on places selected value :
if($('#place').val()=="10"){
$('#totals').val(val + val * per / 100);
}else{
$('#totals').val('');
}
And to add attach the change event also to the #place select :
$('#percent,#input,#place').on('change input', function() {
Hope this helps.
$('#percent,#input,#place').on('change input', function() {
var val = Number($('#input').val()) || 0,
per = Number($('#percent').val()) || 0;
$('#total').val(val + val * per / 100);
if($('#place').val()=="10"){
$('#totals').val(val + val * per / 100);
}else{
$('#totals').val('');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Value
<input type="text" name="gvalue" id="input" class="input" required/>
<br>Percentage
<select name="percent" id="percent" class="input">
<option value="Country" selected>Select Percentage</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
</select>
<br>
Place
<select name="place" id="place" class="input">
<option value="Country" selected>Place</option>
<option value="5">Place 1</option>
<option value="10">Place 2</option>
<option value="15">Place 3</option>
</select>
<br><br>
Final Value
<input type="text" name="flvalue" class="input" id="total" required/>
<input type="text" name="flvalues" class="input" id="totals" required/>

Changing HTML label color with javascript

I have a form that I need to check for no entries and things like that. Right now the form will change the color of the form fields to red but I need it to change the labels to red also. Since labels are not form elements my current method is making it a tad difficult to change the labels as well. Any suggestions I can implement?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Form Test</title>
<script type="text/javascript">
function validate(){
var errors = new Array();
for( var x = 0; x < document.forms[0].elements.length; x++ ){
if( document.forms[0].elements[x].type == "text" ){
if( document.forms[0].elements[x].value == "" ){
errors.push("The " + document.forms[0].elements[x].name + " field cannot be blank.\n");
document.forms[0].elements[x].className = "in_error";
}
}
if( document.forms[0].elements[x].type == "select-one" ){
if( document.forms[0].elements[x].selectedIndex == 0 ){
errors.push( "The " + document.forms[0].elements[x].name + " field cannot be blank.\n" );
document.forms[0].elements[x].className = "in_error";
}
}
if( document.forms[0].elements[x].type == "password" ){
if( document.forms[0].elements[x].value == ""){
errors.push( "The " + document.forms[0].elements[x].name + " field cannot be blank.\n" );
document.forms[0].elements[x].className = "in_error";
}
}
}
if( errors.length == 0 ){
return true;
}else{
clear_errors( errors );
show_errors( errors );
return false;
}
}
function clear_errors( errors ){
var div = document.getElementById( "errors" );
while( div.hasChildNodes() ){
div.removeChild(div.firstChild);
}
}
function show_errors( errors ){
var div = document.getElementById( "errors" );
for(var x = 0; x < errors.length; x++){
var error = document.createTextNode( errors[x] );
var p = document.createElement( "p" );
p.appendChild( error );
div.appendChild( p )
}
}
window.onload = function( ){
document.forms[0].onsubmit = validate;
}
</script>
<style type="text/css">
#errors{
color: #F00;
}
.in_error{
background-color: #F00;
}
</style>
</head>
<body>
<div id="errors"></div>
<form action="http://ingenio.us.com/examples/echo" method="post">
<div class="mainContainer" style="width:650px; margin: 0 auto; text-align:center;">
<div class="contactInfo" style="text-align:center; width:650px;">
<fieldset>
<legend style="text-align:left;">Contact Info</legend>
<label id="firstNameLabel" for="firstName">First Name: </label><input name="First Name" id="firstName" type="text" size="15" maxlength="15" />
<label id="lastNameLabel" for="lastName">Last Name: </label><input name="Last Name" id="lastName" type="text" size="15" maxlength="15" />
<label id="middleInitialLabel" for="middleInitial">Middle Initial: </label><input name="Middle Initial" id="middleInitial" type="text" size="4" maxlength="1" /><br /><br/>
<label id="streetAddressLabel" for="streetAddress">Street Address: </label><input name="Street Address" id="streetAddress" type="text" size="58" maxlength="55" /> <br /><br />
<label id="cityLabel" for="city">City: </label><input name="City" id="city" type="text" size="30" maxlength="28" />
<label id="stateLabel" for="state">State: </label>
<select name="State" id="state">
<option></option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
<option value="IA">Iowa</option>
<option value="KS">Kansas</option>
<option value="KY">Kentucky</option>
<option value="LA">Louisiana</option>
<option value="ME">Maine</option>
<option value="MD">Maryland</option>
<option value="MA">Massachusetts</option>
<option value="MI">Michigan</option>
<option value="MN">Minnesota</option>
<option value="MS">Mississippi</option>
<option value="MO">Missouri</option>
<option value="MT">Montana</option>
<option value="NE">Nebraska</option>
<option value="NV">Nevada</option>
<option value="NH">New Hampshire</option>
<option value="NJ">New Jersey</option>
<option value="NM">New Mexico</option>
<option value="NY">New York</option>
<option value="NC">North Carolina</option>
<option value="ND">North Dakota</option>
<option value="OH">Ohio</option>
<option value="OK">Oklahoma</option>
<option value="OR">Oregon</option>
<option value="PA">Pennsylvania</option>
<option value="RI">Rhode Island</option>
<option value="SC">South Carolina</option>
<option value="SD">South Dakota</option>
<option value="TN">Tennessee</option>
<option value="TX">Texas</option>
<option value="UT">Utah</option>
<option value="VT">Vermont</option>
<option value="VA">Virginia</option>
<option value="WA">Washington</option>
<option value="WV">West Virginia</option>
<option value="WI">Wisconsin</option>
<option value="WY">Wyoming</option>
</select>
<label name="zipLabel" for="zip">Zip: </label><input name="Zip" id="zip" type="text" size="7" maxlength="5" /><br /><br />
</fieldset>
</div><br /><br />
</div>
<div class="mainContainerTwo" style="width:450px; margin: 0 auto; text-align:center;">
<div class="userInfo" style="text-align:center; width:450px;">
<fieldset>
<legend style="text-align:left;">User Info</legend>
<label name="usernameLabel" for="username">Username: </label><input name="Username" id="username" type="text" size="20" maxlength="15" /><br /><br />
<label name="passwordLabel" for="password">Password: </label><input name="Password" id="password" type="password" size="20" maxlength="15" /><br /><br />
<label name="passwordConfirmLabel" for="passwordConfirm">Confirm Password: </label><input name="Confirm Password" id="passwordConfirm" type="password" size="20" maxlength="15" /><br /><br />
<input type="submit" value="Submit" />
</fieldset>
</div>
</div>
</form>
</body>
</html>
A quick fix would be traversing from the input element to the previous sibling, which in this case is the label element. After that you can add class in_error to your label element.
Add the following code line inside the three if-blocks
document.forms[0].elements[x].previousSibling.className = "in_error";
Then you should also change your CSS to the following, in order to set the red background color to the inputs and red foreground color to the labels.
input.in_error{
background-color: #F00;
}
label.in_error {
color: #F00;
}
Is there any reason why you are not using jQuery? If not, I strongly suggest you to take it into use. It makes DOM manipulation like this super easy.

Javascript is not working - help

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Form Validation and Dynamic Forms</title>
<script type="text/javascript">
window.onload = function() {
document.getElementById('shipping1').onclick = calcShipping;
document.getElementById('shipping2').onclick = calcShipping;
document.getElementById('shipping3').onclick = calcShipping;
document.getElementById('Text1').onblur = recalculate;
document.getElementById('Text2').onblur = recalculate;
document.getElementById('Text3').onblur = recalculate;
}
function calcShipping() {
document.getElementById('shippingTbx').value = parseFloat(this.value).toFixed(2);
recalculate();
}
function recalculate() {
var prod1, prod2, prod3;
var prod1$ = 1.5;
var prod2$ = 2.25;
var prod3$ = 3.45;
var merchandise$ = 0;
prod1 = parseInt(document.getElementById('Text1').value);
prod2 = parseInt(document.getElementById('Text2').value);
prod3 = parseInt(document.getElementById('Text3').value);
if (!isNaN(prod1)) {
merchandise$ += (prod1 * prod1$)
}
if (!isNaN(prod2)) {
merchandise$ += (prod2 * prod2$)
}
if (!isNaN(prod3)) {
merchandise$ += (prod3 * prod3$)
}
document.getElementById('merchTbx').value = parseFloat(merchandise$).toFixed(2);
var shipping$ = parseFloat(document.getElementById('shippingTbx').value);
var total$ = merchandise$;
if (!isNaN(shipping$))
total$ += shipping$;
document.getElementById('totalTbx').value = parseFloat(total$).toFixed(2);
}
</script>
<style type="text/css">
body{
background:
#F4F0F4
url(topleft.jpg)
no-repeat
top left;
padding-right: 20px;
padding-bottom: 50px;
font: 0:8em Verdana, sans-serif;}
.row{width:98%; overflow:auto;}
div.header {width:20%; text-align:left;}
div.field { width:75%; text-align:left;}
.style1 {width: 367px}
#Text1
{
width: 58px;
}
#Text2
{
width: 58px;
}
#Text3
{
width: 58px;
}
</style>
</head>
<body >
<h2 style = "text-align:center;">Form Validation and Dynamic Forms</h2>
<table border="10" width="600" align="center" bgcolor="#DEB887">
<tr>
<td class="style1">
<form action= "thankupage.html">
<fieldset>
<legend>Product Information:</legend>
<input type="checkbox" name="Product1" id="Checkbox1" value="yes" tabindex="1" /> Product 1 # 1.50/unit
<input id="Text1" type="text" /><br />
<input type="checkbox" name="Product2" id="Checkbox2" value="yes" tabindex="2" /> Product 2 # 2.25/unit
<input id="Text2" type="text" /><br />
<input type="checkbox" name="Product3" id="Checkbox3" value="yes" tabindex="3" /> Product 3 # 3.45.unit
<input id="Text3" type="text" /><br />
</fieldset>
<br />
<div align="left" style="width: 569px">
<fieldset id="Fieldset2" style="position: relative">
<legend> Billing Address </legend>
<div class="row">
<div class="header">Last Name:</div>
<div class="field"><input type="text" name="lname" tabindex="1" /></div>
</div>
<div class="row">
<div class="header">First Name:</div>
<div class="field"><input type="text" name="lname" tabindex="1" /></div>
</div>
<div class="row">
<div class="header">Address:</div>
<div class="field"><input type="text" name="address" tabindex="3" /></div>
</div>
<div class="row">
<div class="header">City:</div>
<div class="field"><input type="text" name="address" tabindex="3" /></div>
</div>
<div class="row">
<div class="header">State:</div>
<select name="State" id="Select1">
<option value="-1"></option>
<option value="73|0">Alabama</option>
<option value="16|1">Alaska</option>
<option value="70|0">Arizona</option>
<option value="75|0">Arkansas</option>
<option value="71|0">California</option>
<option value="72|0">Colorado</option>
<option value="67|0">Connecticut</option>
<option value="69|0">Delaware</option>
<option value="68|0">District of Columbia</option>
<option value="65|0">Florida</option>
<option value="66|0">Georgia</option>
<option value="62|1">Hawaii</option>
<option value="63|0">Idaho</option>
<option value="58|0">Illinois</option>
<option value="59|0">Indiana</option>
<option value="60|0">Iowa</option>
<option value="55|0">Kansas</option>
<option value="56|0">Kentucky</option>
<option value="57|0">Louisiana</option>
<option value="52|0">Maine</option>
<option value="50|0">Maryland</option>
<option value="51|0">Massachusetts</option>
<option value="47|0">Michigan</option>
<option value="48|0">Minnesota</option>
<option value="49|0">Mississippi</option>
<option value="44|0">Missouri</option>
<option value="45|0">Montana</option>
<option value="46|0">Nebraska</option>
<option value="41|0">Nevada</option>
<option value="42|0">New Hampshire</option>
<option value="43|0">New Jersey</option>
<option value="38|0">New Mexico</option>
<option value="39|0">New York</option>
<option value="40|0">North Carolina</option>
<option value="35|0">North Dakota</option>
<option value="36|0">Ohio</option>
<option value="37|0">Oklahoma</option>
<option value="32|0">Oregon</option>
<option value="34|0">Pennsylvania</option>
<option value="30|0">Rhode Island</option>
<option value="31|0">South Carolina</option>
<option value="26|0">South Dakota</option>
<option value="27|0">Tennessee</option>
<option value="28|0">Texas</option>
<option value="23|0">Utah</option>
<option value="24|0">Vermont</option>
<option value="25|0">Virginia</option>
<option value="21|0">Washington</option>
<option value="22|0">West Virginia</option>
<option value="17|0">Wisconsin</option>
<option value="18|0">Wyoming</option>
<option value="-1">------------------------------------</option>
<option value="19|2">Armed Forces Americas</option>
<option value="14|2">Armed Forces Europe</option>
<option value="15|2">Armed Forces Pacific</option>
<option value="-1">------------------------------------</option>
<option value="74|4">American Samoa</option>
<option value="61|4">Guam</option>
<option value="53|4">Marianas Islands</option>
<option value="54|4">Marshall Islands</option>
<option value="64|4">Micronesia</option>
<option value="33|4">Palau</option>
<option value="29|4">Puerto Rico</option>
<option value="20|4">US Virgin Islands</option>
<option value="-1">------------------------------------</option>
<option value="11|3">Alberta</option>
<option value="12|3">British Columbia</option>
<option value="13|3">Manitoba</option>
<option value="8|3">New Brunswick</option>
<option value="9|3">Newfoundland</option>
<option value="5|3">Northwest Territories</option>
<option value="10|3">Nova Scotia</option>
<option value="6|3">Nunavut</option>
<option value="7|3">Ontario</option>
<option value="2|3">Prince Edward Island</option>
<option value="3|3">Quebec</option>
<option value="4|3">Saskatchewan</option>
<option value="1|3">Yukon</option>
</select>
</div>
<div class="row">
<div class="header">Zip:</div>
<div class="field"><input type="text" name="address" tabindex="3" /></div>
</div>
<div class="row">
<div class="header">Phone Number:</div>
<div class="field"><input type="text" name="pnumber" /></div>
</div>
<div class="row">
<div class="header">email:</div>
<div class="field"><input type="text" name="address" tabindex="3"
style="width: 297px" /></div>
</div>
</fieldset>
</div>
<br />
<fieldset>
<legend> Billing Method </legend>
<input type="radio" onclick="javascript:setTimeout('__doPostBack(\'ctl00$mainContentPlaceHolder$shipMethodSelector$shipMethods$3\',\'\')', 0)" value="3.50" name="Saturday"
id="Radio1"/>
<label for="ctl00_mainContentPlaceHolder_shipMethodSelector_shipMethods_3">Saturday Delivery ($3.50)</label> <br />
<input type="radio" onclick="javascript:setTimeout('__doPostBack(\'ctl00$mainContentPlaceHolder$shipMethodSelector$shipMethods$3\',\'\')', 0)" value="5.00" name="Days"
id="Radio2"/>
<label for="ctl00_mainContentPlaceHolder_shipMethodSelector_shipMethods_3">2-3 days Delivery ($5.00)</label> <br />
<input type="radio" onclick="javascript:setTimeout('__doPostBack(\'ctl00$mainContentPlaceHolder$shipMethodSelector$shipMethods$3\',\'\')', 0)" value="7.50" name="Overnight"
id="Radio3"/>
Overnight<label for="ctl00_mainContentPlaceHolder_shipMethodSelector_shipMethods_3"> Delivery ($7.50)</label>
</fieldset>
<br />
<fieldset>
<legend>Order Summary</legend>
<b> Merchandise: </b>:
<input id="Text4" type="text" /><br />
Shipping charges:
<input id="Text5" type="text" /><br />
Sales Tax:
<input id="Text6" type="text" /><br />
<b> Order Total: </b>:
<input id="Text7" type="text" /></fieldset>
<br />
<fieldset>
<legend>Pay with Credit Card</legend>
<b> Card Type: </b>
<select class="coField7 coFieldError" id="ctl00_mainContentPlaceHolder_creditCardPaymentSelector_currentCreditCard_creditCardList1" name="ctl00$mainContentPlaceHolder$creditCardPaymentSelector$currentCreditCard$creditCardList1">
<option value="0">Select Card</option>
<option value="3">Visa</option>
<option value="4">Master Card</option>
<option value="5">Discover</option>
<option value="7">American Express</option>
</select>
<br />
<b> Card Number: </b>: <input type="text" size="10" />
</fieldset>
<input type="submit" value="Submit" />
<br />
</form>
</td>
</tr>
</table>
</body>
</html>
Try moving your method call away from your window.onload.
window.onload = MyFunction;
function MyFunction()
{
document.getElementById('shipping1').onclick = calcShipping;
document.getElementById('shipping2').onclick = calcShipping;
document.getElementById('shipping3').onclick = calcShipping;
document.getElementById('Text1').onblur = recalculate;
document.getElementById('Text2').onblur = recalculate;
document.getElementById('Text3').onblur = recalculate;
}
Short answer: you don't appear to have any element in the document named "shipping1".
Longer answer: The error you're getting is indicating that something on the line
document.getElementById('shipping1').onclick = calcShipping;
is failing. It can't be document since you're not in a using block and it would be very strange if document could be null. The next object being accessed is whatever is returned by getElementById() for the onclick slot. Since there doesn't appear to be any element with that name in the dcument, it's a pretty good guess that that's causing the problem.
Fix your Radio buttons for shipping. You're calling them 'shipping1,2,3' in javascript, but in your html they have the wrong ID's. Also remove their postback event.
<input type="radio" value="3.50" name="Saturday"
id="Shipping1"/>
<label for="Shipping1">Saturday Delivery ($3.50)</label> <br />
<input type="radio" value="5.00" name="Days"
id="Shipping2"/>
<label for="Shipping2">2-3 days Delivery ($5.00)</label> <br />
<input type="radio" value="7.50" name="Overnight"
id="Shipping3"/>
Overnight<label for="Shipping3"> Delivery ($7.50)</label>
Cheers,
~ck
document.getElementById('shipping1')
Above code is "null", means there is no control with the name "shipping1".
document.getElementById('Text1').onblur
This also throws "null" exception as there is no control with the name "shippingTbx" in the html you gave.
function calcShipping() {
// Below code is null
document.getElementById('shippingTbx').value = parseFloat(this.value).toFixed(2);
recalculate();
}
Please make sure you've all the controls and get the element only for the controls available in the html.

Categories