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.
Related
I need to select a dropdown option based on what my user will enter in a text field. The text field is a number, and the dropdown puts the number in a range to calculate a total based on the price range selected.
The part of the form that deals with this is:
<input name="input_12" id="input_1_20" type="text" value="" class="medium">
<select name="input_15" id="input_1_15">
<option value="0-100 beds|10" price="">0-100 beds </option>
<option value="101-250 beds|7.5" price=" -£ 2.50">101-250 -£ 2.50</option>
<option value="251-500 beds|5" price=" -£ 5.00">251-500 -£ 5.00</option>
<option value="501+ beds|2500" price=" +£ 2,490.00">501+ beds +£ 2,490.00</option>
</select>
The javascript I am using is:
<script>
jQuery('#input_1_20').change(function() {
var selectObj = document.getElementById('input_1_15');
var bedNumber = document.getElementById('input_1_20') ;
if (bedNumber <= '100') {
setSelectedValue(selectObj, "0-100 beds|10"); }
else if (bedNumber <= '250') {
setSelectedValue(selectObj, "101-250 beds|7.5"); }
else if (bedNumber <= '500') {
setSelectedValue(selectObj, "251-500 beds|5"); }
function setSelectedValue(selectObj, valueToSet) {
for (var i = 0; i < selectObj.options.length; i++) {
if (selectObj.options[i].text== valueToSet) {
selectObj.options[i].selected = true;
return;
}
}
}
})
</script>
I'm not getting any javascript errors, but the select field is not being updated. Can anyone advise?
Update: Link to Fiddle - https://jsfiddle.net/xg6ktr1a/
Thanks!
Instead of looping through the select options, try simply setting the value of the select element itself. Here's a comparison of select-value-setting methods from another SO user.
Also, you're trying to use lesser-than/greater-than comparisons on strings, not numbers... so those conditions will never be met. You can fix this by coercing bedNumber to an integer, then checking that number.
jQuery('#input_1_20').change(function() {
var selectObj = document.getElementById('input_1_15');
var bedNumberInput = document.getElementById('input_1_20');
// coerce this value to a Number
var bedNumber = parseInt(bedNumberInput.value);
if (bedNumber <= 100) {
selectObj.value = "0-100 beds|10";
}
else if (bedNumber <= 250) {
selectObj.value = "101-250 beds|7.5";
}
else if (bedNumber <= 500) {
selectObj.value = "251-500 beds|5";
}
else {
selectObj.value = "501+ beds|2500";
}
});
$('#input_1_20').change(function() {
var bedNumber = parseInt(document.getElementById('input_1_20').value);
console.log(bedNumber)
if (bedNumber <= 100) {
$("#input_1_15 option[value='0-100 beds|10']").prop('selected', true);
} else if (bedNumber > 100 && bedNumber <= 250) {
$("#input_1_15 option[value='101-250 beds|7.5']").prop('selected', true);
} else if (bedNumber > 250 && bedNumber <= 500) {
$("#input_1_15 option[value='251-500 beds|5']").prop('selected', true);
} else {
$("#input_1_15 option[value='501+ beds|2500']").prop('selected', true);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input name="input_12" id="input_1_20" type="text" value="" class="medium">
<select name="input_15" id="input_1_15">
<option value="0-100 beds|10" price="">0-100 beds </option>
<option value="101-250 beds|7.5" price=" -£ 2.50">101-250 -£ 2.50</option>
<option value="251-500 beds|5" price=" -£ 5.00">251-500 -£ 5.00</option>
<option value="501+ beds|2500" price=" +£ 2,490.00">501+ beds +£ 2,490.00</option>
</select>
</form>
I have two select element and I want to show some options in second select based on what user choose at first select.
consider first select have two options : a , b ...
if user choose 'a' from first select :
the second select optiones should be -> c , d ...
and if user choose 'b' from first select :
the second select optiones should be : e , f ...
I have done some coding but the problem is at the start when user doesnt choose any option from first select the second select is always empty(it should show c , d)
<!DOCTYPE html>
<html>
<body>
<select id="s1" required>
<option value="a">a</option>
<option value="b">b</option>
</select>
<select id="s2" required > </select>
<script>
document.getElementById("s1").onchange = function() {
document.getElementById('s2').disabled = false; //enabling s2 select
document.getElementById('s2').innerHTML = ""; //clear s2 to avoid conflicts between options values
var opt0 = document.createElement('option');
var opt1 = document.createElement('option');
if (this.value == 'a') {
opt0.textContent = "c";
opt1.textContent = "d";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
} else if (this.value == 'b') {
opt0.textContent = "e";
opt1.textContent = "f";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
}
};
</script>
</body>
</html>
If you can save the option values in a lookup object (or JSON):
function setOptions(select, values) {
for (var i = select.length = values.length; i--; )
select[i].innerText = values[i]
}
function value(select) { return select.value || select[0].value } // 1st item by default
var data = { 1: { 1.1: [1.11, 1.12], 1.2: [1.21, 1.22] },
2: { 2.1: [2.11, 2.12], 2.2: [2.21, 2.22], 2.3: [2.31, 2.32, 2.33] } }
s2.onchange = function() { setOptions(s3, data[value(s1)][value(s2)]) }
s1.onchange = function() { setOptions(s2, Object.keys(data[value(s1)])); s2.onchange() }
setOptions(s1, Object.keys(data)); s1.onchange(); // fill the options
<select id=s1 required size=3></select>
<select id=s2 required size=3></select>
<select id=s3 required size=3></select>
This code is based on JavaScript (No need for jQuery)
change Id name and value (x=="desire_value") according to your code
function myFunction() {
var x = document.getElementById("select1").value;
if (x == "3") document.getElementById("select2").style.display = "block";
else document.getElementById("select2").style.display = "none";
}
<select id="select1" onchange="myFunction()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="select2" style="display: none;">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
You have to write the functionality outside of onchange(). Try the following:
document.getElementById("s1").onchange = function() {
document.getElementById('s2').disabled = false; //enabling s2 select
document.getElementById('s2').innerHTML = ""; //clear s2 to avoid conflicts between options values
var opt0 = document.createElement('option');
var opt1 = document.createElement('option');
if (this.value == 'a') {
opt0.textContent = "c";
opt1.textContent = "d";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
} else if (this.value == 'b') {
opt0.textContent = "e";
opt1.textContent = "f";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
}
};
let element = document.getElementById("s1");
let selOption = element.options[element.selectedIndex].value;
if(selOption == 'a'){
var opt0 = document.createElement('option');
var opt1 = document.createElement('option');
opt0.textContent = "c";
opt1.textContent = "d";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
}
<select id="s1" required>
<option value="a">a</option>
<option value="b">b</option>
</select>
<select id="s2" required > </select>
Why don't you just put that hard coded...
<!DOCTYPE html>
<html>
<body>
<select id="s1" required>
<option value="a">a</option>
<option value="b">b</option>
</select>
<select id="s2" required >
<option value="c">c</option>
<option value="d">d</option>
</select>
<script>
document.getElementById("s1").onchange = function() {
document.getElementById('s2').disabled = false; //enabling s2 select
document.getElementById('s2').innerHTML = ""; //clear s2 to avoid conflicts between options values
var opt0 = document.createElement('option');
var opt1 = document.createElement('option');
if (this.value == 'a') {
opt0.textContent = "c";
opt1.textContent = "d";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
} else if (this.value == 'b') {
opt0.textContent = "e";
opt1.textContent = "f";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
}
};
</script>
</body>
</html>
One approach to contemplate is populating the dependant dropdowns with all values and use a data attribute for the parent-child relationship. Javascript then clones and removes the options for later insertion.
The functional javascript is now very lean and the dependency relationships are maintained in the DOM.
var s2Clone;
// Doesn't work in older IEs
//CLone the Dependant drop down and hide
document.addEventListener('DOMContentLoaded', function(){
s2Clone = document.getElementById("s2").cloneNode(true);
document.getElementById("s2").innerHTML = "";
}, false);
document.getElementById("s1").onchange = function() {
var selected = this.value;
//Get the nodes with a parent attribute of the selected data
var optionsToInsert = s2Clone.querySelectorAll("[data-parent='" + selected +"']");
//clear existing
var s2 = document.getElementById("s2");
s2.innerHTML = "";
//Add The new options.
for(i = 0; i < optionsToInsert.length; i++)
{
s2.appendChild(optionsToInsert[i]);
}
}
<select id="s1" required>
<option value="">Please select</option>
<option value="a">a</option>
<option value="b">b</option>
</select>
<select id="s2" required >
<option value="a1" data-parent="a">a - 1</option>
<option value="a2" data-parent="a">a - 2</option>
<option value="a3" data-parent="a">a - 3</option>
<option value="b1" data-parent="b">b - 1</option>
<option value="b2" data-parent="b">b - 2</option>
<option value="b3" data-parent="b">b - 3</option>
</select>
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;
}
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>
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In my php, I have created two dropdown or selection lists. My drop down list below:
<select name="food">
<option value="">...</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
</select>
<select name="type">
<option value="">--</option>
<option value="Apple">Apple</option>
<option value="Lettuce">Lettuce</option>
<option value="Orange">Orange</option>
<option value="Tomato">Tomato</option>
<option value="Carrots">Carrots</option>
<option value="Mango">Mango</option>
</select>
m one page to the next.
It's possible to do this using jQuery, but it will quickly become unmanageable in a large-scale app or website.
If you go this route, I would avoid using two different select boxes, as this will force you to choose two different names for the form POST, unless you use more jQuery hackery to remedy this problem.
My suggestion is to look at a lightweight JS framework. Knockoutjs has what you need.
Look at this JSFiddle.
var fruitOpts = ["Apple", "Orange", "Mango"];
var vegOpts = ["Lettuce", "Tomato", "Carrots"];
$("#food").change(function () {
var val = $(this).val();
if (val === "") {
return;
}
$("#type").find('option').not(':first').remove().end();
$.each(val === "Fruits" ? fruitOpts : vegOpts, function (i, v) {
$("#type").append("<option value=\"" + v + "\">" + v + "</option>");
});
$.each(val === "Fruits" ? vegOpts : fruitOpts, function (i, v) {
$("#type").append("<option value=\"" + v + "\">" + v + "</option>");
});
});
It's version for two different php pages:
1.php
<script src="1.js"></script>
<a id='link' href='2.php'>go to another page</a>
<select id="food" name="food" onchange="selectFoodType()">
<option value="">...</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
<option value="Berries">Berries</option>
</select>
1.js
function selectFoodType()
{
var link = $('#link');
var type = $('select#food option:selected').val();
link.attr('href', link.attr('href') + '?type=' + type);
}
2.php
<script src="2.js"></script>
<select id='type' name="type" data-type='<?=$_GET['type']?>'>
<option value="">--</option>
<option data-type='Fruits' value="Apple">Apple</option>
<option data-type='Vegetables' value="Tomato">Tomato</option>
<option data-type='Vegetables' value="Carrots">Carrots</option>
<option data-type='Berries' value="Strawberry">Strawberry</option>
</select>
2.js
$(function() {
var type = $('select#type').data('type');
var itemsId = document.getElementById("type");
var items = itemsId.getElementsByTagName("option");
var selected_type = [], other_types = [];
selected_type[0] = items[0];
for (var i = 1; i < items.length; i++){
if ($(items[i]).data('type') === type) {
selected_type.push(items[i]);
continue;
}
other_types.push(items[i]);
}
selected_type = selected_type.sort(sortByName);
other_types = other_types.sort(sortByName);
$.merge(selected_type, other_types);
var list = '';
for (i=0; i<selected_type.length; i++) {
list += selected_type[i].outerHTML;
}
$(items).remove();
$(itemsId).append(list);
});
function sortByName(a, b) {
if (a.text > b.text) return 1;
else if (a.text < b.text) return -1;
return 0;
}
You should assign all Fruits and Vegetables contents in JavaScript object and display related contents of food value in another drop down, see below demo
Food:
<select name="food" id="food">
<option value="">...</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
</select>
Content
<select name="contents" id="contents">
<option value="">...</option>
</select>
JS code
var data = {
'Fruits':['Apple', 'Lettuce', 'Orange', 'Mango'],
'Vegetables': ['Tomato', 'Carrots']
};
document.getElementById("food").onchange = function(Event){
var contents = document.getElementById("contents");
contents.innerHTML = "";
for(var i in data[this.value]){
var option = document.createElement("option");
option.setAttribute('value',data[this.value][i]);
option.text = data[this.value][i];
contents.appendChild(option);
}
var expect_data = Event.target.value == "Fruits" ? "Vegetables" : "Fruits";
for(var i in data[expect_data]){
var option = document.createElement("option");
option.setAttribute('value',data[expect_data][i]);
option.text = data[expect_data][i];
contents.appendChild(option);
}
}
FIDDLE DEMO
you need to use JQuery for this purpose.
See My Solution: http://jsfiddle.net/inventorx/YU4vJ/
Code Here:
HTML
<select name="food" >
<option value="">...</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
</select>
<select name='type' >
<option>-- Select Food Type --</option>
</select>
<select id='Fruits' style='display:none' >
<option value="">--</option>
<option value="Apple">Apple</option>
<option value="Orange">Orange</option>
<option value="Mango">Mango</option>
</select>
<select id='Vegetables' style='display:none' >
<option value="">--</option>
<option value="Lettuce">Lettuce</option>
<option value="Tomato">Tomato</option>
<option value="Carrots">Carrots</option>
</select>
JQUERY
$(document).ready(function(){
$("select[name='food']").on("change", function(){
var value = $(this).val();
$("select[name='type']").html($("#" + value).html());
});
});
Another option.
The list splits into two arrays: food, corresponding to the selected type; and does not correspond to the selected type. Each of these arrays, in turn, is sorted by name:
JSFIDDLE
HTML:
<select id="food" name="food" onchange="selectFoodType()">
<option value="">...</option>
<option value="Fruits">Fruits</option>
<option value="Vegetables">Vegetables</option>
<option value="Berries">Berries</option>
</select>
<select id='type' name="type">
<option value="">--</option>
<option data-type='Fruits' value="Apple">Apple</option>
<option data-type='Vegetables' value="Lettuce">Lettuce</option>
<option data-type='Vegetables' value="Tomato">Tomato</option>
<option data-type='Berries' value="Strawberry">Strawberry</option>
</select>
JQuery:
function selectFoodType()
{
var type = $('select#food option:selected').val();
var itemsId = document.getElementById("type");
var items = itemsId.getElementsByTagName("option");
var selected_type = [], other_types = [];
selected_type[0] = items[0];
for (var i = 1; i < items.length; i++){
if ($(items[i]).data('type') === type) {
selected_type.push(items[i]);
continue;
}
other_types.push(items[i]);
}
selected_type = selected_type.sort(sortByName);
other_types = other_types.sort(sortByName);
$.merge(selected_type, other_types);
var list = '';
for (i=0; i<selected_type.length; i++) {
list += selected_type[i].outerHTML;
}
$(items).remove();
$(itemsId).append(list);
}
function sortByName(a, b) {
if (a.text > b.text) return 1;
else if (a.text < b.text) return -1;
return 0;
}