Calculating the value of radio buttons, select and check boxes - javascript

HI I am doing a menu for a pizza place (Leaning project) where one the user select the radio buttons the the select buttons it calculations the total. Instance at the minute I a chose of three radio buttons small medium and large. and 3 select boxes. each time select box is chosen £1 will be added to the price of the given value of the chosen radio button. For instance if some selects the small radio button that's £4 then they select the next three select box's that's a total of £7 which should be displayed instantly on the screen on each selection. I haven't added the check boxes yet as I have noticed its not working. I got the original script from an on-line tutorial that worked when I tested. But after tying to modify it to suit it seems that the dive that displays the total price wont work.
< body onload = 'hideTotal()' >
< div id = "wrap" >
< form action = ""
id = "pizzaform"
onsubmit = "return false;" >
< div >
< div class = "cont_order" >
< fieldset >
< legend > Make your Pizza! < /legend>
<label >Size Of the Pizza</label > < br / >
Small Pizza 7 "(£4)
<label class='radiolabel'><input type="
radio " name="
selectedpizza " value="
Round1 " onclick="
calculateTotal()
" />Round </label><br />
Large 11" (£6) < label class = 'radiolabel' > < input type = "radio"
name = "selectedpizza"
value = "Round2"
onclick = "calculateTotal()" / > Round < /label><br / >
Midum 15 "(£8)
<label class='radiolabel'><input type="
radio " name="
selectedpizza " value="
Round3 " onclick="
calculateTotal()
" />Round </label><br />
<br />
<label >Sacuce</label>
<select id="
sauce " name='sauce' onchange="
calculateTotal()
">
<option value="
None ">Select Sacuce</option>
<option value="
Enzo 's classic Sauce">Enzo'
s classic Sauce(£1) < /option>
<option value="Spicy Tomato">Spicy Tomato(£1)</option >
< /select>
<br / >
< label > Base < /label>
<select id="base" name='base' onchange="calculateTotal()">
<option value="None">Select Base</option >
< option value = "Thin and cripy" > Thin and cripy(£1) < /option>
<option value="Deep Pan">Deep Pan(£1)</option >
< option value = "Stuffed Crust" > Stuffed Crust(£1) < /option>
</select >
< br / >
< label > Cheese < /label>
<select id="cheese" name='cheese' onchange="calculateTotal()">
<option value="None">Select cheese</option >
< option value = "Mozzarella" > Mozzarella(£1) < /option>
<option value="Reduced Fat">Reduced Fat(£1)</option >
< /select>
<br / >
< div id = "totalPrice" > < /div>
</fieldset >
< /div>
</div >
< /form>
</div > <!--End of wrap-->
< script language = "javascript"
type = "text/javascript" >
/*
This source is shared under the terms of LGPL 3
www.gnu.org/licenses/lgpl.html
You are free to use the code in Commercial or non-commercial projects
*/
//Set up an associative array
//The keys represent the size of the Pizza
//The values represent the cost of the Pizza i.e A 15" Pizza cost's £8
var pizza_prices = new Array();
pizza_prices["Round1"] = 4;
pizza_prices["Round2"] = 6;
pizza_prices["Round3"] = 8;
var sacuce_prices = new Array();
sacuce_prices["None"] = 0;
sacuce_prices["Enzo's classic Sauce"] = 1;
sacuce_prices["Spicy Tomato"] = 1;
var base_prices = new Array();
base_prices["None"] = 0;
base_prices["Thin and cripy"] = 1;
base_pricess["Deep Pan"] = 1;
base_pricess["Stuffed Crust"] = 1;
var cheese_prices = new Array();
cheese_prices["None"] = 0;
cheese_prices["Mozzarella"] = 1;
cheese_prices["Reduced Fat"] = 1;
// getPizzaSizePrice() finds the price based on the size of the Pizza.
// Here, we need to take user's the selection from radio button selection
function getPizzaSizePrice() {
var pizzaSizePrice = 0;
//Get a reference to the form id="pizzaform"
var theForm = document.forms["pizzaform"];
//Get a reference to the Pizza the user Chooses name=selectedPizza":
var selectedPizza = theForm.elements["selectedpizza"];
//Here since there are 4 radio buttons selectedPizza.length = 4
//We loop through each radio buttons
for (var i = 0; i < selectedPizza.length; i++) {
//if the radio button is checked
if (selectedPizza[i].checked) {
//we set PizzaSizePrice to the value of the selected radio button
//i.e. if the user choose the 8" Pizza we set it to 6
//by using the pizza_prices array
//We get the selected Items value
//For example pizza_prices["Round2".value]"
pizzaSizePrice = pizza_prices[selectedPizza[i].value];
//If we get a match then we break out of this loop
//No reason to continue if we get a match
break;
}
}
//We return the PizzaSizePrice
return PizzaSizePrice;
}
function getPizzaSacucePrice() {
var pizzaSaucePrice = 0;
//Get a reference to the form id="cakeform"
var theForm = document.forms["pizzaform"];
//Get a reference to the select id="sauce"
var selectedSauce = theForm.elements["sauce"];
//set pizzaSauce Price equal to value user chose
//For example sauce_prices
pizzaSaucePrice = sauce_prices[selectedSauce.value];
//finally we return pizzaSaucePrice
return PizzaSaucePrice;
}
function getBasePrice() {
var pizzaBasePrice = 0;
//Get a reference to the form id="pizzaform"
var theForm = document.forms["pizzaform"];
//Get a reference to the select id="base"
var selectedBauce = theForm.elements["base"];
//set pizzaBase Price equal to value user chose
//For example base_prices
pizzaBaseePrice = base_prices[selectedBase.value];
//finally we return pizzaSaucePrice
return pizzaBasePrice;
}
function getCheesePrice() {
var pizzaCheesePrice = 0;
//Get a reference to the form id="pizzaform"
var theForm = document.forms["pizzaform"];
//Get a reference to the select id="cheese"
var selectedCheese = theForm.elements["cheese"];
//set pizzaCheese Price equal to value user chose
//For example cheese_prices
pizzaBaseePrice = cheese_prices[selectedSauce.value];
//finally we return pizzaCheesePrice;
return PizzaCheesePrice;
}
function calculateTotal() {
//Here we get the total price by calling our function
//Each function returns a number so by calling them we add the values they return together
var pizzaPrice = getPizzaSizePrice() + getSacucePrice() + getBasePrice() + getCheesePrice();
//display the result
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'block';
divobj.innerHTML = "Total Price For the Pizza £" + pizzaPrice;
}
function hideTotal() {
var divobj = document.getElementById('totalPrice');
divobj.style.display = 'none';
}
< /script>
<body onload='hideTotal()'>
<div id="wrap">
<form action="" id="pizzaform" onsubmit="return false;">
<div>
<div class="cont_order">
<fieldset>
<legend>Make your Pizza!</legend>
<label>Size Of the Pizza</label>
<br />Small Pizza 7"(£4)
<label class='radiolabel'>
<input type="radio" name="selectedpizza" value="Round1" onclick="calculateTotal()" />Round</label>
<br />Large 11"(£6)
<label class='radiolabel'>
<input type="radio" name="selectedpizza" value="Round2" onclick="calculateTotal()" />Round</label>
<br />Midum 15"(£8)
<label class='radiolabel'>
<input type="radio" name="selectedpizza" value="Round3" onclick="calculateTotal()" />Round</label>
<br />
<br />
<label>Sacuce</label>
<select id="sauce" name='sauce' onchange="calculateTotal()">
<option value="None">Select Sacuce</option>
<option value="Enzo's classic Sauce">Enzo's classic Sauce(£1)</option>
<option value="Spicy Tomato">Spicy Tomato(£1)</option>
</select>
<br />
<label>Base</label>
<select id="base" name='base' onchange="calculateTotal()">
<option value="None">Select Base</option>
<option value="Thin and cripy">Thin and cripy(£1)</option>
<option value="Deep Pan">Deep Pan(£1)</option>
<option value="Stuffed Crust">Stuffed Crust(£1)</option>
</select>
<br />
<label>Cheese</label>
<select id="cheese" name='cheese' onchange="calculateTotal()">
<option value="None">Select cheese</option>
<option value="Mozzarella">Mozzarella(£1)</option>
<option value="Reduced Fat">Reduced Fat(£1)</option>
</select>
<br />
<div id="totalPrice"></div>
</fieldset>
</div>
</div>
</form>
</div>
<!--End of wrap-->
Can any one help? Also I plan on give the user a choice of 10 toppings using check boxes is there a way of limiting the user so they can only choose 4 out of the choice of 10?

Data attributes would work well for both purposes.
Counting the total
Use data-price on radios, checkboxes and options:
<form id="my-form">
<input type="radio" data-price="100" name="radio">Add 1GBP
<input type="radio" data-price="200" name="radio">Add 2GBP
<select>
<option>Select something</option>
<option data-price="300">Add 3GB</option>
<option data-price="400">Add 4GB</option>
</select>
</form>
Total: <span id="my-total"></span>
Then count them on every page load and form change with jQuery:
$('#my-form').on('change', function(){
update_total();
});
function update_total(){
var tot = 0;
var price = 0;
$('#my-form input:checked').each(function(){
price = $(this).data('price');
if(price > 0){
tot += price;
}
});
$('#my-form select').each(function(){
price = $("option:selected", this).data('price');
if(price > 0){
tot += price;
}
});
$('#my-total').html(tot);
}
update_total();
Limiting checkboxes
Use data-max-check to define the maximum amount of checkboxes that can be checked in a given container:
<div data-max-check="4">
<input type="checkbox">
<input type="checkbox">...
Then stop the user from selecting more than the maximum with jQuery:
$('[data-max-check] input[type=checkbox]').on('click', function(e){
var $parent = $(this).closest('[data-max-check]');
var max = $parent.data('max-check');
var chk = $parent.find('input[type=checkbox]:checked').size();
if(chk > max){
alert('You can only select up to ' + max);
e.preventDefault();
}
});
Demo
You can see both in action here: JSFiddle

Related

How to can I get array elements by Id to do Comparisons?

My find matches function does not seem to be working.
I want to get an array ([]) element by id and do comparisons with it.
The function is supposed to go into the array and generate a random person, then display the match in the text area "showmatches".
I am not sure if the random person is being generated nor if the criteria are being matched in the comparison.
<html>
<head>
<script>
var records = [];
function calculateAge()
{
var dob = document.getElementById('dob').value;
var dobInput = new Date(dob);
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var day = now.getDate();
var birthyear = dobInput.getFullYear();
var birthmonth = dobInput.getMonth();
var birthday = dobInput.getDate();
var bYear = year - birthyear;
var bMonth = month - birthmonth;
var bDay = day - birthday;
if (bYear < 18 || bYear > 75)
{
alert("Age cannot be less than 18 or greater than 75");
return false;
}else{
document.getElementById("age").value = bYear + "years old";
}
//document.getElementById("age").value = bYear + "years old";
}
function showAll()
{
show = document.getElementById("showallpersons").innerHTML=records;
show.value = records.join("\n");
}
(window.onload = () => {
var findmatches=document.getElementById('findmatches');
if(findmatches){
findmatches.addEventListener('click', findMatches, false);
}
function findMatches(e)
{
e.preventDefault();
for(var counter=0; counter<records.length; counter++)
{
var currposn = records[counter].value;
var show = document.getElementById("showallmatches").innerHTML= currposn.fname + currposn.lname;
show.value = currposn.join("\n");
do
{
//From here
var randpson = Math.random() * records.length;
randpson = Math.floor(randpson); //To here works, I know that for sure
//I'm not sure if the conditions for the if statements are correct
if(((randpson.age - currposn.age) <= 10) || ((randpson.age - currposn.age) >= 20))
{
if(((randpson.height - currposn.height) <= 10) || ((randpson.height - currposn.height) >= 20))
{
var display = document.getElementById("showmatches").innerHTML= "Matched to: " +randpson.fname + randpson.lname;
//display.value = "Matched to: " + randpson.fname + randpson.lname;
break;
}
}
} while(counter < 10){
//var newDisplay = document.getElementById("showallmatches").innerHTML= null;
}
//console.log(findMatches());
}
}
})()
(window.onload = () => {
var submit = document.getElementById('submit');
if(submit){
submit.addEventListener('click', addnew, false);
}
function addnew(event)
{
//Prevents default submit event
event.preventDefault();
//Accept values entered in form
var fname = document.getElementById('fname').value;
var mname = document.getElementById('mname').value;
var lname= document.getElementById('lname').value;
var dob= document.getElementById('dob').value;
var gender = document.forms['Information']['gender'].value;
var age = document.getElementById('age').value;
parseInt(age);
var bodyType = document.getElementById('Body Type').value;
var occu= document.getElementById('occu').value;
var height= document.getElementById('height').value;
if (fname==null || fname=="")
{
alert("A first name is required");
return false;
}
if(mname==null || mname=="")
{
alert("A middle initial is required");
return false;
}
if (lname==null || lname=="")
{
alert("A last name is required");
return false;
}
if(dob==null || dob=="")
{
alert("A DOB is required");
return false;
}
if (gender == "")
{
alert("Please select a gender");
return false;
}
if(height <= 170 || height >= 200)
{
alert("A height between 170, not less and 200, not more is required");
return false;
}
if(bodyType==null || bodyType==""){
alert("Please choose a body type");
return false;
}
if(occu==null || occu=="")
{
alert("Please enter an occupation");
return false;
}
//Append To array
records.push(fname);
records.push(mname);
records.push(lname);
records.push(gender);
records.push(age);
records.push(bodyType);
records.push(occu);
records.push(height);
for(i=0;i<records.length;i++)
{
console.log(records[i]);
}
document.getElementById("Information").reset();
}
})()
</script>
</head>
<body>
<div class="wrapper">
<header class="page-header">
<nav>
<button class="cta-contact">Contact Us</button>
</nav>
</header>
</div>
<div class="space">
<h1>
<marquee behavior="scroll" direction="right">What are you waiting for? Find your "one" now.</marquee>
</h1>
</div>
<div class="container">
<form name="Information" id="Information">
<fieldset>
<legend>Personal Information</legend>
First Name:
<input id="fname" type="text" size=40 placeholder='First Name' minlength=4 maxlength=40 required />
<br/><br/>
Middle Initial:
<input id="mname" type="text" size=3 placeholder='M Intial' maxlength=1 required />
<br/><br/>
Last Name:
<input id="lname" type="text" size='40' placeholder='Last Name' minlength='4' maxlength='40' required />
<br/><br/>
Date of Birth
<input id="dob" type="date" onchange="calculateAge()"/>
<br/><br/>
Gender:
<input id="male" type="radio" value='M' name="gender" required/> Male
<input id="female" type="radio" value='F' name="gender" required/> Female
<br/><br/>
Age: <input type="text" id="age" disabled />
<br/>
Body Type:
<select id="Body Type">
<optgroup label="Female" id="FemaleOpt">
<option value="Apple"> Apple </option>
<option value="Pear"> Pear </option>
<option value="Pencil"> Pencil </option>
<option value="Hourglass"> Hourglass </option>
<option value="Round"> Round </option>
</optgroup>
<optgroup label="Male" id="MaleOpt">
<option value="Oval"> Oval </option>
<option value="Triangle"> Triangle </option>
<option value="Rectangle"> Rectangle </option>
<option value="Rhomboid">Rhomboid </option>
<option value="Inverted">Inverted Triangle</option>
</optgroup>
</select>
<br/><br/>
Occupation:
<input id="occu" type="text" size=30 maxlength=30 required />
<br/><br/>
Height(in cm):
<input id="height" type="number" size="3" min="171" max="199" value="" required /><br>
<br/><br/>
<textarea id="showallpersons" name="Show All Persons" onclick="showAll()" disabled></textarea>
<textarea id="showmatches" name="Show All Matches" onclick="findMatches()" disabled></textarea>
<br/><br/>
<button id="submit" type="submit">Submit</button>
<button id="findmatches" type="button">Find Matches</button>
</fieldset>
</form>
</div>
</body>
</html>
Do these steps. First you have two window.onload = () (As you are not using addEventListener only one event will be attached).
Steps:
Keep everything intact, just remove the window.onload from both places. Keep all code inside load intact.
Move the entire code block just to the bottom of the html above closing tag. (Doing so, will make window.onload redundant.)
Put console.log() in the click handler and see if it's working (it will)
Let us know.
NOTE: On other hand there are better way to code this, for e.g wait for DOMContentLoaded for attaching event etc., but it's too big to discuss here. First make this work, then we can recommend better approaches.

How can I save a total score in localstorage each time a checkbox is checked

I've built a small game using checkboxes with images. When the user comes across the item in the picture they select the checkbox and the message changes on screen. Because this is a tourist guide website and game, the user will leave the page to look at other pages, selecting the pictures as they come across the item. Therefore I needed to save the checked boxes in localstorage so that the data persists. I have some javascript that dsave the checked boxes.
Each picture has a value and when the image is clicked it adds to an overall total. I can't get this total to persist if the page is refreshed or closed and reopened.
My javascript for calculating the total and storing the checkboxes is below.
$('.dp-spotter-switch input[type="checkbox"]').click(function () {
if (!$(this).is(':checked')) {
$(this).parent('.dp-spotter-switch').removeClass('spotter-scale');
} else {
$(this).parent('.dp-spotter-switch').addClass('spotter-scale');
}
});
function showDiv() {
document.getElementById('getScoreLabel').style.display = "block";
}
// Total values
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "" + total.toFixed(0);
}
// Store checkbox state
(function () {
var boxes = document.querySelectorAll("input[type='checkbox']");
for (var i = 0; i < boxes.length; i++) {
var box = boxes[i];
if (box.hasAttribute("store")) {
setupBox(box);
}
}
function setupBox(box) {
var storageId = box.getAttribute("store");
var oldVal = localStorage.getItem(storageId);
console.log(oldVal);
box.checked = oldVal === "true" ? true : false;
box.addEventListener("change", function () {
localStorage.setItem(storageId, this.checked);
});
}
})();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="dp-spotter-container">
<div class="dp-top-paragraph">
<p>Some text</p>
<p>Click on the photos once you have spotted, and at the end click on <strong>Get Your Score</strong> to see how you've done</p>
<div id="getScoreLabel" style="display:none; text-align: center;">
<div class="dp-your-score-text" id="getScore">Your Score</div>
<input value="0" readonly="readonly" type="text" id="total" class="dp-scores dp-floating"/>
</div>
</div>
<br/>
<br/>
<!-- Spotter 1 -->
<div class="dp-switch-container">
<label class="dp-spotter-switch">
<img class="dp-spotter-img" src="image.jpg">
<input type="checkbox" name="product" value="3" id="cb1" class="spotter-check" onclick="totalIt()" store="checkbox1">
<span class="dp-spotter-slider"></span>
<span class="dp-spotter-text-label">Item 1- 3 Points</span>
</label>
</div>
<!-- Spotter 2 -->
<div class="dp-switch-container">
<label class="dp-spotter-switch">
<img class="dp-spotter-img" src="image.jpg">
<input type="checkbox" name="product" value="3" id="cb2" class="spotter-check" onclick="totalIt()" store="checkbox2">
<span class="dp-spotter-slider"></span>
<p class="dp-spotter-text-label">Item 2 - 3 Points</p>
</label>
</div>
<!-- Spotter 3 -->
<div class="dp-switch-container">
<label class="dp-spotter-switch">
<img class="dp-spotter-img" src="image.jpg">
<input type="checkbox" name="product" value="5" id="cb3" class="spotter-check" onclick="totalIt()" store="checkbox3">
<span class="dp-spotter-slider"></span>
<p class="dp-spotter-text-label">ITem 3 - 5 Points</p>
</label>
</div>
<!-- Spotter 4 -->
<div class="dp-switch-container">
<label class="dp-spotter-switch">
<img class="dp-spotter-img" src="image.jpg">
<input type="checkbox" name="product" value="10" id="cb4ß" class="spotter-check" onclick="totalIt()" store="checkbox4">
<span class="dp-spotter-slider"></span>
<p class="dp-spotter-text-label">Item 4 - 10 Points</p>
</label>
</div>
Get Your Score
</div>
I'm looking for a way to add to the existing function for the checkboxes if possible.
Unfortunately we can't use local storage in StackOverflow runnable code snippets, so you'll have to head over to my repl.it to see this working in action.
Since you're using jQuery, I've gone ahead and provided a jQuery solution:
Used .attr() to set the checkbox based on local storage
Called totalIt when showing showDiv
If you want to use your existing code, just change box.checked = oldVal === "true" ? true : false; to box.setAttribute('checked', oldVal === "true" ? true : false) and add totalIt to your showDiv function
Demo
https://repl.it/#AnonymousSB/SO53500148
Solution
function showDiv() {
totalIt();
document.getElementById('getScoreLabel').style.display = "block";
}
// Total values
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementById("total").value = "" + total.toFixed(0);
}
// Store checkbox state
function setupBox(box) {
var storageId = box.attr("store");
var oldVal = localStorage.getItem(storageId);
box.attr('checked', oldVal === "true" ? true : false)
box.change(function() {
localStorage.setItem(storageId, this.checked);
});
}
$(document).ready(function () {
$( "input[type='checkbox'][store]" ).each(function( index ) {
setupBox($( this ));
});
})
You can open Chrome Dev Tools, go to Application, and see your local storage

Javascript form calculation errors

Im getting uncaught type error for estimateCost, also im having issues with how to double the price with spouse. I'm suppose to have an alert window that displays the estimate cost based on selections made from city, number of days, and other options. TY!
<html>
<head>
<script language="JavaScript">
var city_prices = new Array();
city_prices["New York City"] = 0;
city_prices["Boston"] = 0;
city_prices["San Francisco"] = 200;
city_prices["Los Angeles"] = 200;
// getCityPrice() finds the price based on the city .
// Here, we need to take user's the selection from radio button selection
function getCityPrice() {
var cityPrice = 0;
//Get a reference to the form id="cakeform"
var theForm = document.forms["form1"];
//Get a reference to the cake the user Chooses name=radCity":
var selectedCity = theForm.elements["radCity"];
//Here since there are 4 radio buttons selectedCity.length = 4
//We loop through each radio buttons
for (var i = 0; i < selectedCity.length; i++) {
//if the radio button is checked
if (selectedCity[i].checked) {
//we set cityPrice to the value of the selected radio button
//i.e. if the user choose NYC we set to 0
//by using the city_prices array
//We get the selected Items value
//For example city_prices["New York City".value]"
cityPrice = city_prices[selectedCity[i].value];
//If we get a match then we break out of this loop
//No reason to continue if we get a match
break;
}
}
//We return the cityPrice
return cityPrice;
}
var number_days = new Array();
number_days["3"] = 450;
number_days["4"] = 600;
number_days["5"] = 750;
number_days["6"] = 900;
number_days["7"] = 1050;
number_days["8"] = 1350;
number_days["9"] = 1500;
number_days["10"] = 1650;
number_days["11"] = 1800;
number_days["12"] = 1950;
number_days["13"] = 2100;
number_days["14"] = 2250;
number_days["15"] = 2400;
//This function finds the day price based on the
//drop down selection
function getDayPrice() {
var dayPrice = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the select id="selNumberDays"
var selectedDays = theForm.elements["selNumberDays"];
//set dayPrice equal to value user chose
//For example number_days["3".value] would be equal to 450
dayPrice = number_days[selectedDays.value];
//finally we return dayPrice
return dayPrice;
}
//chksFirst() finds the candles price based on a check box selection
function chksFirst() {
var chkFirst = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the checkbox id="chkFirst"
var includeFirst = theForm.elements["chkFirst"];
//If they checked the box set first class to 500
if (includeFirst.checked == true) {
chkFirst = 500;
}
//finally we return the firstClass
return chkFirst;
}
//chksSpouse() finds the candles price based on a check box selection
function chksSpouse() {
var chkSpouse = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the checkbox id="chkSpouse"
var includeSpouse = theForm.elements["chkSpouse"];
//If they checked the box set Total 2x
if (includeSpouse.checked == true) {
totalPrice = totalPrice * 2;
}
//finally we return the firstClass
return totalPrice;
}
function estimateCost() {
//Here we get the estimate price by calling our function
//Each function returns a number so by calling them we add the values they return together
var totalPrice = getCityPrice() + getDayPrice() +
chksFirst() + chksSpouse();
alert(totalPrice);
}
</script>
</head>
<body>
<table align="left" width="600px" border="0" cellpadding="5px">
<tr>
<td>
<form name="form1" id="form1">
<table border="0">
<tr>
<td width="300px"><strong>Last Name: </strong>
</td>
<td width="300px">
<input type="text" name="txtFirstName" value=" " size="20" />
</td>
</tr>
<tr>
<td><strong>First Name: </strong>
</td>
<td>
<input type="text" name="txtLastName" value=" " size="20" />
</td>
</tr>
<tr>
<td><strong>Nationality: </strong>
</td>
<td>
<select name="selNationality">
<option value="amer">USA</option>
<option value="can">Canada</option>
<option value="mex">Mexico</option>
<option value="ger">Germany</option>
<option value="fra">France</option>
</select>
</td>
</tr>
<tr>
<td><strong>City you wish to visit: </strong>
</td>
<td>
<input type="radio" name="radCity" value="New York City" />New York City
<br />
<input type="radio" name="radCity" value="Boston" />Boston
<br />
<input type="radio" name="radCity" value="San Francisco" />San Francisco ($200 surcharge)
<br />
<input type="radio" name="radCity" value="Los Angeles" />Los Angeles ($200 surcharge)
<br/>
</td>
</tr>
<tr>
<td><strong>Number of days ($150 per day): </strong>
</td>
<td>
<select name="selNumberDays" id="selNumberDays">
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
</td>
</tr>
<tr>
<td><strong>Other options: </strong>
</td>
<td>
<input type="checkbox" name="chkFirst" id="chkFirst" />First Class Only ($500 surcharge)
<br />
<input type="checkbox" name="chkSpouse" id="chkSpouse" />Traveling with Spouse (All costs doubled)
<br />
</td>
</tr>
<tr>
<td align="right">
<input type="button" value="Give me an estimate!" onClick="estimateCost()" id="estimateCost" />
</td>
<td align="left">
<input type="reset" />
</td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
On the button input with the onClick="estimateCost()" code, remove the id="estimateCost". It's causing the error for some reason. You should really be using an onClick listener though instead of an inline onclick:
Inline onclick JavaScript variable
For the total with spouse, you might want to rework it to something like this where you pass the pre-spouse price into the chksSpouse function and use it's return as the total price.
//chksSpouse() finds the candles price based on a check box selection
function chksSpouse(totalPrice) {
var chkSpouse = 0;
//Get a reference to the form id="form1"
var theForm = document.forms["form1"];
//Get a reference to the checkbox id="chkSpouse"
var includeSpouse = theForm.elements["chkSpouse"];
//If they checked the box set Total 2x
if (includeSpouse.checked == true) {
totalPrice = totalPrice * 2;
}
//finally we return the firstClass
return totalPrice;
}
function estimateCost() {
//Here we get the estimate price by calling our function
//Each function returns a number so by calling them we add the values they return together
var preSpouseTotal = getCityPrice() + getDayPrice() + chksFirst();
var totalPrice = chksSpouse(preSpouseTotal);
alert(totalPrice);
}

Limit the number of check-boxes allowed to be checked

function CountChecks(whichlist,forarray,maxchecked,latestcheck) {
// An array containing the id of each checkbox to monitor.
// List the id of each checkbox in the set. If more than
// one set, list other sets in their own arrays. The
// array name to use is passed to this function.
*// THIS PART IMPORTANT*//
var listone = new Array("1", "2", "3", "4", "5", "6");
*// THIS PART IMPORTANT*//
// End of customization.
var iterationlist;
eval("iterationlist="+whichlist);
var count = 0;
for( var i=0; i<iterationlist.length; i++ ) {
if( document.getElementById(iterationlist[i]).checked == true) { count++; }
if( count > maxchecked ) { latestcheck.checked = false; }
}
if( count > maxchecked ) {
alert('Sorry, only ' + maxchecked + ' may be checked.');
}
}
This is you can see CHECKBOX CHECK LIMITER.. And you can see works with function. I wanna do send this to js file from the page.. but Its not very functional becouse of array part. It has to create array's own by own.. I add the variable function part 'forarray'.. I dont know javascript and Im asking you it has to be like this when it create own arrays.
var {whichlist variable} = new Array({forarray variable list});
And HTML code like this.
<p>
Check up to 3 sizes:<br>
<input id='1' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','1',3,this)" value="2x2">2x2
<input id='2' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','2',3,this)" value="2x2.5">2x2.5
<input id='3' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','3',3,this)" value="2x3">2x3
<input id='4' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','4',3,this)" value="2.5x2.5">2.5x2.5
<input id='5' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','5',3,this)" value="2.5x3">2.5x3
<input id='6' type="checkbox" name="boxsize[]" onclick="CountChecks('listone','6',3,this)" value="3x3">3x3
</p>
<p>
Check up to 2 colors:<br>
<input id='7' type="checkbox" name="favoritecolor[]" onclick="CountChecks('listtwo','7',2,this)" value="red">Red
<input id='8' type="checkbox" name="favoritecolor[]" onclick="CountChecks('listtwo','8',2,this)" value="gold">Gold
<input id='9' type="checkbox" name="favoritecolor[]" onclick="CountChecks('listtwo','9',2,this)" value="green">Green
<input id='10' type="checkbox" name="favoritecolor[]" onclick="CountChecks('listtwo','10',2,this)" value="silver">Silver
<input id='11' type="checkbox" name="favoritecolor[]" onclick="CountChecks('listtwo','11',2,this)" value="blue">Blue
</p>
You do not need to do all of that. All you need to do is pass a reference to the element into the function and then use its name to query a list of its siblings. Count the number of checked boxes and prevent any others from being checked.
<p>
Check up to 3 sizes:<br>
<input id='1' type="checkbox" name="listone" onclick="javascript:checkNumChecked(this, 3)"
value="2x2">2x2
<input id='2' type="checkbox" name="listone" onclick="checkNumChecked(this,3)" value="2x2.5">2x2.5
<input id='3' type="checkbox" name="listone" onclick="checkNumChecked(this,3)" value="2x3">2x3
<input id='4' type="checkbox" name="listone" onclick="checkNumChecked(this,3)" value="2.5x2.5">2.5x2.5
<input id='5' type="checkbox" name="listone" onclick="checkNumChecked(this,3)" value="2.5x3">2.5x3
<input id='6' type="checkbox" name="listone" onclick="checkNumChecked(this,3)" value="3x3">3x3
</p>
<p>
Check up to 2 colors:<br>
<input id='7' type="checkbox" name="listtwo" onclick="checkNumChecked(this,2)" value="red">Red
<input id='8' type="checkbox" name="listtwo" onclick="checkNumChecked(this,2)" value="gold">Gold
<input id='9' type="checkbox" name="listtwo" onclick="checkNumChecked(this,2)" value="green">Green
<input id='10' type="checkbox" name="listtwo" onclick="checkNumChecked(this,2)" value="silver">Silver
<input id='11' type="checkbox" name="listtwo" onclick="checkNumChecked(this,2)" value="blue">Blue
</p>
<script>
function checkNumChecked(ele, limit) {
var ct = 0, siblings = document.getElementsByName(ele.name), checked = 0;
for (ct = 0; ct <= siblings.length - 1; ct++) {
checked += (siblings[ct].checked) ? 1 : 0
if (checked > limit) {
siblings[ct].checked = false
alert('Sorry, only ' + limit + ' item(s) may be checked.');
break;
}
}
}
</script>
However, alerts are annoying to end users. A much better way of doing this is to disable the other check boxes once the limit has been reached and re-enable them when a box is unchecked.
<script>
function checkNumChecked(ele, limit) {
var ct = 0, siblings = document.getElementsByName(ele.name), checked = 0;
for (ct = 0; ct <= siblings.length - 1; ct++) {
checked += (siblings[ct].checked) ? 1 : 0
}
for (ct = 0; ct <= siblings.length - 1; ct++) {
siblings[ct].disabled = siblings[ct].checked ? false : (checked == limit) ? true : false
}
}
</script>
To have the same, but make it work using only ids you can do the following:
<script>
function checkNumChecked(ele, limit) {
var ct = 0, siblings = [], checked = 0, item_num = parseInt(ele.id),
sct = (item_num < 7) ? 1 : 7, ect = (item_num < 7) ? 6 : 11;
for (ct = sct; ct <= ect; ct++) {
siblings.push(document.getElementById(ct));
}
for (ct = 0; ct <= siblings.length - 1; ct++) {
checked += (siblings[ct].checked) ? 1 : 0
}
for (ct = 0; ct <= siblings.length - 1; ct++) {
siblings[ct].disabled = siblings[ct].checked ? false : (checked == limit) ? true : false
}
}
</script>

Enable dropdown after typing all the values in textbox

In my HTML form, there are 2 textbox and one dropdown.
While loading the page, dropdown should not be editable(ie: disabled)
After filling all the textbox,the dropdown should be editable.
Please give an idea to solve this in javascript.
Try like this
HTML
<input type="text" id="text1" onblur="myFunction()">
<input type="text" id="text2" onblur="myFunction()">
<select id="select1" disabled>
<option>value</option>
</select>
Javascript
function myFunction() {
if (document.getElementById("text1").value.length > 0 && document.getElementById("text2").value.length > 0) {
document.getElementById("select1").disabled = false;
} else {
document.getElementById("select1").disabled = true;
}
}
Check both input elements value whenever keyup event is fired. If both the input elements have no inputs then disable the select element. Else enable it. Try this way,
javaScript :
function SetControlState(){
for(var i = 0; i < inputs.length; i++){
if(inputs[i].value.length == 0){
selectddl.disabled = true;
break;
} else{
selectddl.disabled = false;
}
}
}
var selectddl = document.getElementById("dropdl");
var inputs = document.getElementsByTagName('input');
var isEnabled = false;
for(var i = 0; i < inputs.length; i++){
if(inputs[i].id == 'first' || inputs[i].id == 'second'){
inputs[i].onkeyup = function(){
SetControlState();
};
}
}
HTML :
<select name="ddl" id="dropdl" disabled="true">
<option value="A">A</option>
<option value="B">B</option>
</select>
<input type="text" id="first"/>
<input type="text" id="second"/>
jsFiddle

Categories