I have a form that has a function to perform calculations and I cannot get it to work properly although its not throwing any errors in the console. When I check the checkbox, it doesn't stay checked. When I select the province from the drop down menu basically it should set the appropriate government fee, our fee and the tax value.
//my array
var price_govStatus = new Array(14)
price_govStatus[0] = 17.50 //Alberta
price_govStatus[1] = 26.68 //British Columbia
price_govStatus[2] = 35 //Manitoba
price_govStatus[3] = 20 //New Brunswick
price_govStatus[4] = 10 //Newfoundland
price_govStatus[5] = 10 //Northwest Territories
price_govStatus[6] = 37.40 //Nova Scotia
price_govStatus[7] = 10 //Nunavut
price_govStatus[8] = 26.00 //Ontario
price_govStatus[9] = 30 //Prince Edward Island
price_govStatus[10] = 34.34 //Quebec
price_govStatus[11] = 20 //Saskatchewan
price_govStatus[12] = 15 //Yukon
price_govStatus[13] = 10 //Canada
function checkJurisdictions() {
if ((theForm.Corporate_Profile_Report.checked == true) && (theForm.corpsearchprov.selectedIndex >= 0) )
{
dis_govfee_corporate_profile_report = price_govCorpProfile[theForm.corpsearchprov.selectedIndex];
theForm.dis_govfee_corporate_profile_report.value = formatCurrency(price_govCorpProfile[theForm.corpsearchprov.selectedIndex]);
}
else
{
dis_govfee_corporate_profile_report = 0;
theForm.dis_govfee_corporate_profile_report.value = formatCurrency('0.00');
}
if ((theForm.Certificate_Status.checked == true) && (theForm.statusprov.selectedIndex != 6))
{
dis_govfee_certstatus = price_govStatus[theForm.statusprov.selectedIndex];
theForm.dis_govfee_certstatus.value = formatCurrency(price_govStatus[theForm.statusprov.selectedIndex]);
dis_ourfee_certstatus = 30;
theForm.dis_ourfee_certstatus.value = formatCurrency('30.00');
dis_tax_certstatus = 3.90;
}
else if ((theForm.Certificate_Status.checked == true) && (theForm.statusprov.selectedIndex = 6))
{
dis_govfee_certstatus = 37.40;
theForm.dis_govfee_certstatus.value = formatCurrency('37.40');
dis_ourfee_certstatus = 35;
theForm.dis_ourfee_certstatus.value = formatCurrency('35.00');
dis_tax_certstatus = 4.55;
}
else if (theForm.Certificate_Status.checked == false)
{
dis_govfee_certstatus = 0;
theForm.dis_govfee_certstatus.value = formatCurrency('0.00');
dis_ourfee_certstatus = 0;
theForm.dis_ourfee_certstatus.value = formatCurrency('0.00');
dis_tax_certstatus = 0;
}
}
My HTML
<select onChange="Form_Calculator();" id="statusprov" name="statusprov">
<option value="Alberta">Alberta</option>
<option value="British Columbia">British Columbia</option>
<option value="Manitoba">Manitoba</option>
<option value="New Brunswick">New Brunswick</option>
<option value="Newfoundland">Newfoundland</option>
<option value="Northwest Territories">Northwest Territories</option>
<option value="Nova Scotia">Nova Scotia</option>
<option value="Nunavut">Nunavut</option>
<option value="Ontario">Ontario</option>
<option value="Prince Edward Island">Prince Edward Island</option>
<option value="Quebec">Quebec</option>
<option value="Saskatchewan">Saskatchewan</option>
<option value="Yukon">Yukon</option>
<option value="Canada">Canada</option>
</select>
Related
I'm new to jquery, and i wanted to convert my javascript code that includes two select tags one main and the other for sub, clicking a different option in the main will display a different sub select tag because all of my select tags display are set to none, but i dont know how to structure a jquery
here's my HTML for my select tag
<select name="category" id="c_type" onchange="selectChoice()">
<option value=""></option>
<option value="Learning Environment">Learning Environment</option>
<option value="Learning Support">Learning Support</option>
<option value="Technology Support">Technology Support</option>
<option value="Wellness">Wellness, Health, and Nutrition</option>
<option value="Training">Training and Skills Development</option>
<option value="Financial">Financial Support and Subsidy</option>
<option value="Assistive">Assistive Learning Devices for Students with Special Needs</option>
</select>
<select name="specifics1" id="LE" style="display:none">
<option value=""></option>
<option value="Classroom">Classroom</option>
<option value="Laboratory Room">Laboratory Room</option>
</select>
<select name="specifics2" id="LS" style="display:none">
<option value=""></option>
<option value="Lab Equipments">Lab Equipments</option>
<option value="School Supplies">School Supplies</option>
</select>
<select name="specifics3" id="TS" style="display:none">
<option value=""></option>
<option value="Computer Units">Computer Units</option>
<option value="Internet">Internet Connectivity</option>
</select>
<select name="specifics4" id="WT" style="display:none">
<option value=""></option">
<option value="Feeding">Feeding Program</option>
<option value="Medical Kits">Medical Kits</option>
</select>
<select name="specifics5" id="TAD" style="display:none">
<option value=""></option>
<option value="Pupil Training">Student/Pupil Training</option>
<option value="Literacy Training">Literacy Training</option>
</select>
<select name="specifics6" id="FIN" style="display:none">
<option value=""></option>
<option value="Fare">Fare</option>
<option value="Meals">Meals</option>
</select>
<select name="specifics7" id="ASL" style="display:none">
<option value=""></option>
<option value="Braile">Braile</option>
<option value="Hearing Aids">Hearing Aids</option>
</select>
finally here is my javascript
function selectChoice(){
var main = document.getElementById("c_type").value;
var s1 = document.getElementById("LE");
var s2 = document.getElementById("LS");
var s3 = document.getElementById("TS");
var s4 = document.getElementById("WT");
var s5 = document.getElementById("TAD");
var s6 = document.getElementById("FIN");
var s7 = document.getElementById("ASL");
if(main === "Learning Environment"){
s1.style.display = "block";
s2.style.display = "none";
s3.style.display = "none";
s4.style.display = "none";
s5.style.display = "none";
s6.style.display = "none";
s7.style.display = "none";
s1.required = true;
s2.required = false;
s3.required = false;
s4.required = false;
s5.required = false;
s6.required = false;
s7.required = false;
s1.selectedIndex = 0;
s2.selectedIndex = 0;
s3.selectedIndex = 0;
s4.selectedIndex = 0;
s5.selectedIndex = 0;
s6.selectedIndex = 0;
s7.selectedIndex = 0;
}else if(main === "Learning Support"){
s1.style.display = "none";
s2.style.display = "block";
s3.style.display = "none";
s4.style.display = "none";
s5.style.display = "none";
s6.style.display = "none";
s7.style.display = "none";
s1.required = false;
s2.required = true;
s3.required = false;
s4.required = false;
s5.required = false;
s6.required = false;
s7.required = false;
s1.selectedIndex = 0;
s2.selectedIndex = 0;
s3.selectedIndex = 0;
s4.selectedIndex = 0;
s5.selectedIndex = 0;
s6.selectedIndex = 0;
s7.selectedIndex = 0;
}else if(main === "Technology Support"){
s1.style.display = "none";
s2.style.display = "none";
s3.style.display = "block";
s4.style.display = "none";
s5.style.display = "none";
s6.style.display = "none";
s7.style.display = "none";
s1.required = false;
s2.required = false;
s3.required = true;
s4.required = false;
s5.required = false;
s6.required = false;
s7.required = false;
s1.selectedIndex = 0;
s2.selectedIndex = 0;
s3.selectedIndex = 0;
s4.selectedIndex = 0;
s5.selectedIndex = 0;
s6.selectedIndex = 0;
s7.selectedIndex = 0;
}}
Looking at it i have 7 sub select tags with different select names and ids so it will be probably long but its working, what i want is to shorten it using jquery but i don't know how,
IMHO here is the shortest way to write a similar code, and much easier to maintain
const Category = [
{ type:'Learning Environment', ref:'LE', specs: [ 'Classroom', 'Laboratory Room' ] }
, { type:'Learning Support', ref:'LS', specs: [ 'Lab Equipments', 'School Supplies' ] }
, { type:'Technology Support', ref:'TS', specs: [ 'Computer Units', 'Internet Connectivity' ] }
, { type:'Wellness, Health, and Nutrition', ref:'WT', specs: [ 'Feeding Program', 'Medical Kits' ] }
, { type:'Training and Skills Development', ref:'TAD', specs: [ 'Student/Pupil Training', 'Literacy Training' ] }
, { type:'Financial Support and Subsidy', ref:'FIN', specs: [ 'Fare', 'Meals' ] }
, { type:'Assistive Learning Devices for Students with Special Needs', ref:'ASL', specs: [ 'Braile', 'Hearing Aids' ] }
];
const Select_category = document.querySelector('#c_type')
, Select_specs = document.querySelector('#specs')
;
// first initialisation on load...
let item = 0;
Select_category[item++] = new Option('','');
for (let cat of Category)
{
Select_category[item++] = new Option(cat.type, cat.ref );
}
// ... end initialisation.
Select_category.onchange = function()
{
Select_specs.innerHTML = null;
if (Select_category.value === ''){
Select_specs.classList.add('noDisplay');
}
else
{
let item = 0;
Select_specs[item++] = new Option('','');
Category.find(cat=>cat.ref===Select_category.value).specs.forEach((spec,index)=>{
Select_specs[item++] = new Option(spec, index );
})
Select_specs.classList.remove('noDisplay');
}
}
.noDisplay { display: none; }
<select name="category" id="c_type" ></select>
<select name="specs" id="specs" class="noDisplay"></select>
I added my html and js snippet however it still not completed. Sorry if the code is a bit messy this is my first attempt for me to build something like this on my own.
`
var selectBread = document.querySelectorAll(".bread-select");
var sauceSelect = document.querySelectorAll(".sauces-select");
var checkBoxes = document.getElementsByTagName("input");
var orderModal = document.getElementById("order-modal");
let chosenItem;
let chosenItemPrice;
var ingredients = [];
var ingredientsPrice = [];
let selectedItem;
var sideDishes = [];
var drink = [];
var toasted;
var currentSandwich = {};
var breadAndPrice = [
["baguette", 0.8],
["burger bun", 0.8],
["ciabatta", 0.9],
["focaccia", 1.5],
["ftira", 0.8],
["olive bread", 1.3],
["rye bread", 1.3],
["sliced bread", 0.9],
["tortilla", 1.6],
["wheat bread", 0.9],
["whole grain bread", 1.2]
];
var sauceAndPrice = [
["chili sauce", 0.25],
["garlic and olive oil", 0.35],
["ketchup", 0.15],
["mayonnaisee", 0.15],
["garlic basil mayo", 0.45],
["mustard", 0.25]
];
function getBreadInfo(el, currentOption) {
for (var i = 0; i < el.length; i++) {
//add event listener to all bread select menu options
el[i].addEventListener("change", function() {
selectedItem = event.target.value; //current selected item
getArrIndex(currentOption, selectedItem);
if (event.target.name === "bread-select") {
currentSandwich.breadType = chosenItem;
currentSandwich.breadPrice = chosenItemPrice;
} else if (event.target.name === "sauce-select") {
currentSandwich.sauce = chosenItem;
currentSandwich.saucePrice = chosenItemPrice;
} else if (event.target.name === "side-dishes-select") {
currentSandwich.sideDish = chosenItem;
currentSandwich.sideDishPrice = chosenItemPrice;
} else if (event.target.name === "drinks-select") {
currentSandwich.drinkSelect = chosenItem;
currentSandwich.drinkPrice = chosenItemPrice;
} else if (event.target.name === "toasted-select") {
currentSandwich.toasted = chosenItem;
}
});
}
}
function getArrIndex(arr, val) {
// val is the selected item
for (var i = 0; i < arr.length; i++) {
//iterate through the current choosen array
if (arr[i][0] === val) {
// when selected item is found in the array
chosenItem = arr[i][0]; // store the item in choosenItem value
chosenItemPrice = arr[i][1]; // store the item price in choosenItem value
}
}
}
getBreadInfo(selectBread, breadAndPrice);
getBreadInfo(sauceSelect, sauceAndPrice);
//get the index of the selected item from the bread and price array
function getIngredientsInfo() {
for (var i = 0; i < checkBoxes.length; i++) {
//loop check boxes
checkBoxes[i].addEventListener("change", function() {
//add event listener to check boxes
if (event.target.checked) {
//check if check boxes are checked
ingredients.push(event.target.name); //push the name of ingredient to ingredients array
ingredientsPrice.push(event.target.value); //get the price of the item checked from value attr and push it to ingredientsPrice array
} else if (event.target.checked === false) {
var index = ingredients.indexOf(event.target.name);
ingredients.splice(index, 1);
ingredientsPrice.splice(index, 1);
}
});
}
}
getIngredientsInfo();
<section class="order-section">
<h2 class="selection-header">Choose your...</h2>
<div class="select-container">
<select class="bread-select" name="bread-select">
<option selected disabled>Bread Type</option>
<option value="baguette">Baguette</option>
<option value="burger bun">Burger Bun</option>
<option value="ciabatta">Ciabatta</option>
<option value="focaccia">Focaccia</option>
<option value="ftira">Ftira</option>
<option value="olive bread">Olive Bread</option>
<option value="rye bread">Rye Bread</option>
<option value="sliced bread">Sliced Bread</option>
<option value="tortilla">Tortilla</option>
<option value="wheat bread">Wheat Bread</option>
<option value="whole grain bread">Whole Grain Bread</option>
</select>
<select class="sauces-select" name="sauce-select">
<option selected disabled>Sauces</option>
<option value="chili sauce">Chili Sauce</option>
<option value="garlic and olive oil">Garlic and Olive Oil</option>
<option value="ketchup">Ketchup</option>
<option value="mayonnaise">Mayonnaise</option>
<option value="garlic basil mayo">Garlic Basil Mayo</option>
<option value="mustard">Mustard</option>
</select>
<select class="side-dishes-select" name="side-dishes-select">
<option selected disabled>Side Dishes</option>
<option value="coleslaw">Coleslaw</option>
<option value="curly fries">Curly Fries</option>
<option value="mixed salad">Mixed Salad</option>
<option value="potato wedges">Potato Wedges</option>
<option value="potatoes salad">Potatoes Salad</option>
<option value="sliced Potatoes fries">Sliced Potatoes Fries</option>
<option value="sweet potatoes fries">Sweet Potatoes Fries</option>
</select>
<select class="drinks-select" name="drinks-select">
<option selected disabled>Drinks</option>
<option value="Still Water">Still Water</option>
<option value="Fizzy Water">Fizzy Water</option>
<option value="coca cola">Coca Cola</option>
<option value="sprite">Sprite</option>
<option value="fanta">Fanta</option>
<option value="kinnie">Kinnie</option>
<option value="cisk">Cisk</option>
</select>
<select class="toasted-select" name="toasted-select">
<option selected disabled>Toasted</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
</section>
`I have a function which I am using to get data from select menus and I would like to save the data to an object by passing it as an argument. At the moment the only solution I found is to use if statements but it look bad. Any help to refactor this please?
if (event.target.name === "bread-select") {
currentSandwich.breadType = chosenItem;
currentSandwich.breadPrice = chosenItemPrice;
} else if (event.target.name === "sauce-select") {
currentSandwich.sauce = chosenItem;
currentSandwich.saucePrice = chosenItemPrice;
} else if (event.target.name === "side-dishes-select") {
currentSandwich.sideDish = chosenItem;
currentSandwich.sideDishPrice = chosenItemPrice;
} else if (event.target.name === "drinks-select") {
currentSandwich.drinkSelect = chosenItem;
currentSandwich.drinkPrice = chosenItemPrice;
} else if (event.target.name === "toasted-select") {
currentSandwich.toasted = chosenItem;
}
I'd suggest the switch is the way to go, it is both faster and better practice.
switch(event.target.name) {
case 'bread-select':
currentSandwich.breadType = chosenItem;
currentSandwich.breadPrice = chosenItemPrice;
break;
...
default:
}
Thanks
You can use a string to make a property assignment to and object using [] bracket notation. So if you are able to get a relevant property name, or part of a property name from your selects, that should work for you.
var selects = document.querySelectorAll('select');
for(var i = 0; i < selects.length; i++){
selects[i].addEventListener('change', selectHandler);
}
var currentSandwich = {};
var prices = {
soda : .5,
tea : .5,
lemonade : 1,
water : 0,
corn : 2,
potatoes : 2.5,
carrots : 1.5
};
function selectHandler(evt){
var name = evt.target.name;
var selection = evt.target.value;
currentSandwich[name] = selection;
if(prices[selection]){
currentSandwich[name+"price"] = prices[selection];
}else{
currentSandwich[name+"price"] = 0;
}
console.log(currentSandwich);
}
<select name='drink'>
<option value=''>Please Choose One</option>
<option value='soda'>Soda</option>
<option value='tea'>Tea</option>
<option value='lemonade'>Lemonade</option>
<option value='water'>Water</option>
</select>
<select name='side'>
<option value=''>Please Choose One</option>
<option value='corn'>Corn</option>
<option value='potatoes'>Potatoes</option>
<option value='carrots'>Carrots</option>
</select>
This is a significantly different approach. It stores prices and some keys in the HTML markup, and uses a simple function to use these to update your sandwich.
I don't know if this sort of refactoring is what you were looking for, but it's one reasonable way to avoid such repetitive logic.
var sandwich = {};
var sandwichContainer = document.getElementById('sandwich-options');
sandwichContainer.addEventListener('change', function(ev) {
var select = event.target;
var choice = select.selectedOptions[0];
var choiceName = select.dataset.choiceName;
sandwich[choiceName] = choice.value
var priceName = select.dataset.choicePrice;
if (priceName) {
sandwich[priceName] = Number(choice.dataset.price);
}
console.log(sandwich)
});
<section class="order-section">
<h2 class="selection-header">Choose your...</h2>
<div id="sandwich-options">
<select class="bread-select" name="bread-select"
data-choice-name="breadType" data-choice-price="breadPrice">
<option selected disabled>Bread Type</option>
<option value="baguette" data-price="0.8">Baguette</option>
<option value="burger bun" data-price="0.8">Burger Bun</option>
<option value="ciabatta" data-price="0.9">Ciabatta</option>
<option value="focaccia" data-price="1.5">Focaccia</option>
<option value="ftira" data-price="0.8">Ftira</option>
<option value="olive bread" data-price="1.3">Olive Bread</option>
<option value="rye bread" data-price="1.3">Rye Bread</option>
<option value="sliced bread" data-price="0.9">Sliced Bread</option>
<option value="tortilla" data-price="1.6">Tortilla</option>
<option value="wheat bread" data-price="0.9">Wheat Bread</option>
<option value="whole grain bread" data-price="1.2">Whole Grain Bread</option>
</select>
<select class="sauces-select" name="sauce-select" data-
choice-name="sauce", data-choice-price="saucePrice">
<option selected disabled>Sauces</option>
<option value="chili sauce" data-price="0.25">Chili Sauce</option>
<option value="garlic and olive oil" data-price="0.35">Garlic and Olive Oil</option>
<option value="ketchup" data-price="0.15">Ketchup</option>
<option value="mayonnaise" data-price="0.15">Mayonnaise</option>
<option value="garlic basil mayo" data-price="0.45"
>Garlic Basil Mayo</option>
<option value="mustard" data-price="0.25">Mustard</option>
</select>
<select class="toasted-select" name="toasted-select" data-choice-name="toasted">
<option selected disabled>Toasted</option>
<option value="yes" data-price="0">Yes</option>
<option value="no" data-price="0">No</option>
</select>
</div>
</section>
An alternate approach would be to store all your prices in a object keyed by the select names, something like this:
var prices = {
'bread-select': {
'baguette': 0.8,
...
},
'sauces-select': {
'chili sauce': 0.25,
...
},
...
};
and then use select.name and choice.value from the above to key into this object. You would also need another object, or a way to enhance this one to store the final property names.
Below are my codes which allows user to select multiple values from the drop down list and when the user clicks the button 'Go' the selected values will be displayed on the new page. I've also created classes for both attributes in order to list the selected values.
Unfortunately, when the button is clicked after selections, nothing is being displayed. Need help on this.
"mainTest.html" page.
< script type = "text/javascript" >
(function() {
/**
* Handles the click of the submit button.
*/
function onSubmitClicked(event) {
var url = 'newPageTest.html?';
var foodbevs = document.getElementsByClassName('foodbeverage');
for (var i = 0; i < foodbevs.length; i++) {
if (i > 0) url += '&';
url += 'foodbeverage=' + encodeURIComponent(foodbevs[i].value);
}
var statuses = document.getElementsByClassName('status');
for (i = 0; i < statuses.length; i++) {
url += '&status=' + encodeURIComponent(statuses[i].value);
}
location.href = url;
}
// Get the button from the DOM.
var submitButton = document.getElementById('btngo');
// Add an event listener for the click event.
submitButton.addEventListener('click', onSubmitClicked);
})();
<
/script>
<!DOCTYPE html>
<html>
<body>
<h4 style="color:darkblue">Choose Your Food/Beverage & Quantity : </h4>
<table>
<tr>
<td>
<B>Choose a Food/Beverage : </B>
<select class="foodbeverage">
<optgroup label="DEFAULT">
<option value = "NONE">NONE</option>
</optgroup>
<optgroup label="Food">
<option value = "Chicken Chop">Chicken Chop</option>
<option value = "Pasta">Pasta</option>
<option value = "Pizza">Pizza</option>
<option value = "Chocolate Cake">Chocolate Cake</option>
<option value = "Red Velvet Cake">Red Velvet Cake</option>
<option value = "Ice Cream Cake">Ice Cream Cake</option>
</optgroup>
<optgroup label="Beverages">
<option value = "Milk">Milk</option>
<option value = "Fresh Juice">Fresh Juice</option>
<option value = "Ice Cream">Ice Cream</option>
<option value = "Coffee">Coffee</option>
<option value = "Carbonated Can Drink">Carbonated Can Drink</option>
<option value = "Water">Water</option>
</optgroup>
</select>
<br/>
<B>Choose a Food/Beverage : </B>
<select class="foodbeverage">
<optgroup label="DEFAULT">
<option value = "NONE">NONE</option>
</optgroup>
<optgroup label="Food">
<option value = "Chicken Chop">Chicken Chop</option>
<option value = "Pasta">Pasta</option>
<option value = "Pizza">Pizza</option>
<option value = "Chocolate Cake">Chocolate Cake</option>
<option value = "Red Velvet Cake">Red Velvet Cake</option>
<option value = "Ice Cream Cake">Ice Cream Cake</option>
</optgroup>
<optgroup label="Beverages">
<option value = "Milk">Milk</option>
<option value = "Fresh Juice">Fresh Juice</option>
<option value = "Ice Cream">Ice Cream</option>
<option value = "Coffee">Coffee</option>
<option value = "Carbonated Can Drink">Carbonated Can Drink</option>
<option value = "Water">Water</option>
</optgroup>
</select>
<br/>
</td>
<td>
<B>Dine In or Take Away : </B>
<select class="status">
<optgroup label="DEFAULT">
<option value = "NONE">NONE</option>
</optgroup>
<optgroup label="Status">
<option value = "Dine In">Dine In</option>
<option value = "Take Away">Take Away</option>
</optgroup>
</select>
<br/>
<B>Dine In or Take Away : </B>
<select class="status">
<optgroup label="DEFAULT">
<option value = "NONE">NONE</option>
</optgroup>
<optgroup label="Status">
<option value = "Dine In">Dine In</option>
<option value = "Take Away">Take Away</option>
</optgroup>
</select>
<br/>
</td>
</tr>
</table>
<br/>
<br/>
<input type="submit" id="btngo" value="Go" />
<br/>
</body>
</html>
"newPageTest.html" page.
< script type = "text/javascript" >
function parseQuery(str) {
if (typeof str != "string" || str.length == 0) return {};
var s = str.split("&");
var s_length = s.length;
var bit, query = {},
first, second;
for (var i = 0; i < s_length; i++) {
bit = s[i].split("=");
first = decodeURIComponent(bit[0]);
if (first.length == 0) continue;
second = decodeURIComponent(bit[1]);
if (typeof query[first] == "undefined") query[first] = second;
else if (query[first] instanceof Array) query[first].push(second);
else query[first] = [query[first], second];
}
return query;
}
//Function to update "showdata" div with URL Querystring parameter values
function passParameters() {
window.onload = passParameters;
var query = parseQuery(window.location.search);
var data = "<b>Food Beverages:</b> " + query.foodbeverage + " <b>Dine/Takeaway:</b> " + query.status;
document.getElementById("showdata").innerHTML = data;
}
<
/script>
<!DOCTYPE html>
<html>
<body>
<div id="showdata"></div>
</body>
</html>
I find 2 mistake from your code.
Put the window.onload = passParameters; outside of your passParameters function.
For example:
function passParameters() {
var query = parseQuery(window.location.search);
var data = "<b>Food Beverages:</b> " + query.foodbeverage + " <b>Dine/Takeaway:</b> " + query.status;
document.getElementById("showdata").innerHTML = data;
}
window.onload = passParameters;
The parseQuery return {"?foodbeverage":"Chicken Chop","foodbeverage":"Pasta","status":["Dine In","Take Away"]} from input query ?foodbeverage=Chicken%20Chop&foodbeverage=Pasta&status=Dine%20In&status=Take%20Away
You may want to add str = str.substr(1); before var s = str.split("&");
For example
function parseQuery(str) {
if (typeof str != "string" || str.length == 0) return {};
str = str.substr(1);
var s = str.split("&");
var s_length = s.length;
var bit, query = {},
first, second;
for (var i = 0; i < s_length; i++) {
bit = s[i].split("=");
first = decodeURIComponent(bit[0]);
if (first.length == 0) continue;
second = decodeURIComponent(bit[1]);
if (typeof query[first] == "undefined") query[first] = second;
else if (query[first] instanceof Array) query[first].push(second);
else query[first] = [query[first], second];
}
return query;
}
This is a piece of the code I'm working with and the only part giving me problems. I'm using the combo box to give me both the Line2_flag and the screencharge. Without this particular piece of code the form works fine so I know it's just this snippet. Any help is appreciated. Thanks!
<select name="inkcolors" size="1" id="inkcolors" class="FormStyle"
<option selected value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
var = Line2_flag;
var = screencharge;
if(form.inkcolors[1].selected){
Line2_flag = 1.75;
screencharge = 1;
}
if(form.inkcolors[2].selected){
Line2_flag = 2.25;
screencharge = 2;
}
if(form.inkcolors[3].selected){
Line2_flag = 2.75;
screencharge = 3;
}
you could try this method:
<html>
<form>
<select name="inkcolors" size="1" id="inkcolors" class="FormStyle"
<option selected value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</form>
<script>
var Line2_flag = null;
var screencharge = null;
var field = document.forms[0].elements['inkcolors'];
var selected = field.options[field.selectedIndex].value;
if (selected === "1") {
Line2_flag = 1.75;
screencharge = 1;
} else if (selected === "2") {
Line2_flag = 2.25;
screencharge = 2;
} else if (selected === "3") {
Line2_flag = 2.75;
screencharge = 3;
}
</script>
</html>
I ve built a form that displays results according what the users select. I am trying to put an if statement together which will output datasheet 1 on choosing the specific values.
I want when somebody choose the 525 and the 134 and the 290 to give me datasheet 1 else give me the datasheet 3. Here is my code:
<form name="test" id="test"">
<label for="select1">Height in (mm)</label>
<select name="division-select" id="height">
<option label="Please Select"></option>
<option value="525">525 or less</option>
<option value="645">645 or less</option>
<option value="1265">up to 1265</option>
<option value="1270">more than 1265</option>
</select>
<label for="select1">Width in (mm)</label>
<select name="division-select" id="width">
<option label="Please Select"></option>
<option value="134w">134 or less</option>
<option value="190w">190 or less </option>
<option value="290w">290 or less</option>
<option value="328w">328 or less</option>
<option value="420w">420 or more</option>
</select>
<Br>
<br>
<label for="select1">Depth in (mm)</label>
<select name="division-select" id="depth">
<option label="Please Select"></option>
<option value="134d">134 or less</option>
<option value="190d">190 or less </option>
<option value="290d">290 or less</option>
<option value="328d">328 or less</option>
<option value="420d">420 or more</option>
</select>
<br><br>
<h2>Or select by load</h2>
<label for="select1">Load in (kN)</label>
<select name="division-select" id="load">
<option label="Please Select"></option>
<option value="2-5">2.5 or less</option>
<option value="5">5 or less </option>
<option value="10">10 or less</option>
<option value="25">25 or less</option>
<option value="50">50 or more</option>
</select>
<br>
<p><input type="button" onclick="calculate();" value="Find your Datasheet" /><input type="button" onclick="formReset()" value="Reset form"></p>
</form>
<div id="result">
</div>
<script type="text/javascript">
function calculate() {
var height = document.getElementById('height').value;
var width = document.getElementById('width').value;
var depth = document.getElementById('depth').value;
var load = document.getElementById('load').value;
if (document.getElementById("height").value == "") {
var heightmsg = "Please select your sample's height.";
document.getElementById("result").innerHTML = heightmsg;
return false;
}
if (document.getElementById("width").value == "") {
var widthmsg = "Please select your sample's width.";
document.getElementById("result").innerHTML = widthmsg;
return false;
}
if (document.getElementById("depth").value == "") {
var depthmsg = "Please select your sample's depth.";
document.getElementById("result").innerHTML = depthmsg;
return false;
}
if (height === "525" && width === "134" && depth === "290") {
if (height === "525" && width === "290" && depth === "134") {
var str = 'Download your Datasheet 1';
} else {
var str = 'Download your Datasheet 3';
}
} else if (height == 1270) {
var str = "This configuration is beyond the standard range of top-load testers. Please contact Mecmesin Sales to discuss ways to meet your requirements.";
}
document.getElementById("result").innerHTML = str;
}
function formReset() {
document.getElementById("test").reset();
}
</script>
Thanks in advance.
Your width and depth values end in w and d (e.g. <option value="190d">) but you're not checking for that in your if conditions (if (height === "525" && width === "134" && depth === "290")). Take the w and d out of the values like this:
<select name="division-select" id="width">
<option label="Please Select"></option>
<option value="134">134 or less</option>
<option value="190">190 or less</option>
<option value="290">290 or less</option>
<option value="328">328 or less</option>
<option value="420">420 or more</option>
</select>
jsFiddle example
Side note: you have a condition which appears to never be able to be true:
if (height === "525" && width === "134" && depth === "290") {
if (height === "525" && width === "290" && depth === "134")...
if (height === "525" && width === "134" && depth === "290") {
if (height === "525" && width === "290" && depth === "134") {
makes no sense. If the first condition is true, the second never can be. I guess you want
if (height === "525" && width === "290" && depth === "134")
var str = 'Download your Datasheet 1';
else if (height === "525" && width === "134" && depth === "290")
var str = 'Download your Datasheet 3';
else if (height == 1270)
var str = "This configuration is beyond the standard range of top-load testers. Please contact Mecmesin Sales to discuss ways to meet your requirements.";
Also notice that the values of your <option> tags are suffixed with w and d, so they won't equal the suffix-less numbers.
you are using too many if statements, if you want to specify a seperate link for every option from the three select inputs (width, height, depth) you'll end up with 4x5x5 = 100 if statements. the easiest way around this is to create a mysql databases with all the values and correspondents links, alternatively you can use XML or JSON array.
for the empty select input validation you can use:
var height = document.getElementById('height'),
width = document.getElementById('width'),
depth = document.getElementById('depth'),
load = document.getElementById('load'),
result = document.getElementById('result'),
arr = [height, width, depth],
error = "Please select your sample's ";
for (var i = 0; i < arr.length; i++) {
var t = arr[i].id;
if (arr[i].value == "") result.innerHTML = error + t;
return false;
}
for JSON example see the Demo here on jsfiddle.