I have 2 dropdown menus, and I need to compose a link with it's values.
Here is the code:
<form id="dropdown1">
<select id="linha">
<option value="G12">Option 1</option>
<option value="G11">Option 2</option>
<option value="H89">Option 3</option>
</select>
<select id="dia">
<option value="all">Every day</option>
<option value="work">working days</option>
<option value="sat">saturday</option>
<option value="sun">sunday</option>
</select>
</form>
I need something in JavaScript to "compose" a link with http://somewebsite.com/*selected_linha_value*/*selected_dia_value*
How can I do that?
<select name="dia" id="dia">
<option value="all">Every day</option>
<option value="http://stackoverflow.com">working days</option>
<option value="http://anotherSite.com">saturday</option>
<option value="http://anotherSite2.com">sunday</option>
</select>
<script>
$("#dia").change(function () {
var selctedValue = "";
$("select option:selected").each(function () {
selctedValue += $(this).val();
window.location.href = selctedValue;
});
});
i think u need something like this.
<script type="text/javascript">
params = getParams();
var name1 = unescape(params["linha"]);
switch(name1)
{
case "g12":
window.location = "http://www.google.com"
}
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
Its not the full code. It will give you some idea. If you have any doubt just comment
Take a look at: http://jsfiddle.net/ERHhA/
You can use jQuery val() to get the value of the select boxes. Then just append these values to the base url.
var url = "http://somewebsite.com/" + $('#linha').val() + "/" + $('#dia').val();
What about this one?
function make_url(){
var linha = document.getElementById('linha').value;
var dia = document.getElementById('dia').value;
var url=window.location.href;
var pos=url.indexOf('?');
if (pos>-1){
url = url.substr(0,pos);
}
//alert(url + '?linha='+linha+'&dia='+dia); return;
document.location.href = url + '?linha='+linha+'&dia='+dia;
}
fiddle
HTML
<div class="container">
<select class="small-nav">
<option value="" selected="selected">Go To</option>
<option value="http://whiterabbitexpress.com">Services</option>
<option value="http://shop.whiterabbitjapan.com">Shop</option>
</div><!-- container -->
JScript:
$(".small-nav").change(function() {
window.location = $(this).find("option:selected").val();
});
Related
By default selected AUTO category - its ok.
But I want that make and serie should be Not selected - by default.
When I change category from AUTO to MOTO still should be not selected make and serie with empty Not selected - value. Than if I select make, serie should be with empty Not selected - value.
I placed my code here what I have for now:
var $clonedOpts = $("#make_select").children().clone();
$(".tab a").click(function() {
var $layOpts = $clonedOpts.clone().filter('[value^=' + $(this).data("val") + ']');
$("#make_select").html($layOpts);
});
$(".tab a").eq(0).click();
$(document).ready(function() {
var optarray = $("#serie_select").children('option').map(function() {
var selected = '';
if($(this).attr('selected')){
selected = "selected='"+ $(this).attr('selected')+"'";
}
return {
"value": this.value,
"option": "<option value='" + this.value + "' "+selected+" >" + this.text + "</option>"
}
})
$("#make_select").change(function() {
$("#serie_select").children('option').remove();
var addoptarr = [];
for (i = 0; i < optarray.length; i++) {
if (optarray[i].value.indexOf($(this).val()) > -1) {
addoptarr.push(optarray[i].option);
}
}
$("#serie_select").html(addoptarr.join(''))
}).change();
})
a:hover {
cursor:pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tab">
Choose category:<br>
<a data-val="auto">AUTO</a> / <a data-val="moto">MOTO</a>
</div>
<br>
Make:
<select id="make_select">
<option value="">Not selected</option>
<option value="auto_audi">AUDI</option>
<option value="auto_bmw">BMW</option>
<option value="moto_kawasaki">Kawasaki</option>
<option value="moto_harley-davidson">Harley Davidson</option>
</select>
Serie:
<select id="serie_select">
<option value="">Not selected</option>
<option value="auto_audi_a6">A6</option>
<option value="auto_audi_a8">A8</option>
<option value="auto_bmw_x3">X3</option>
<option value="auto_bmw_x5">X6</option>
<option value="moto_kawasaki_ninja">Ninja</option>
<option value="moto_kawasaki_z900">Z900</option>
<option value="moto_harley-davidson_street-750">Street 750</option>
<option value="moto_harley-davidson_sportster-1200">Sportster 1200</option>
</select>
My solution for you. You can add data easily !
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tab">
Choose category:<br>
<a class="clickChoice" data-val="auto">AUTO</a> / <a class="clickChoice" data-val="moto">MOTO</a>
</div>
<br>
Make:
<select id="make_select">
<option value="">Not selected</option>
</select>
Serie:
<select id="serie_select">
<option>Not selected</option>
</select>
<script>
var main_category = ["auto", "moto"];
var makeArr = [];
makeArr['auto'] = ["audi", "bmw"];
makeArr['moto'] = ["kawwa", "honda"];
var serieArr = [];
serieArr['audi'] = ["X1", "X2"];
serieArr['bmw'] = ["N1", "N2"];
serieArr['kawwa'] = ["Ninja1000", "NinjaH2"];
serieArr['honda'] = ["CBR1000", "CBR250"];
$(document).ready(function() {
$(".clickChoice").click(function(k){
var category = $(this).data("val");
var makeList = makeArr[category];
$('#make_select')
.find('option')
.remove()
.end()
.append("<option>Select value</option>")
;
makeList.forEach(function(x) {
$('#make_select').append("<option value="+x+">"+x.toUpperCase()+"</option>");
});
});
$('#make_select').on('change', function() {
var makeValue = this.value;
var serieList = serieArr[makeValue];
console.log(makeValue);
$('#serie_select')
.find('option')
.remove()
.end()
.append("<option>Select value</option>")
;
serieList.forEach(function(x) {
$('#serie_select').append("<option value="+x+">"+x.toUpperCase()+"</option>");
});
});
})
</script>
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>
I have the following HTML and JS, I am trying to only display elements if they match the criteria selected in the <select> tags. I am fairly sure that my IF statement currently would not achieve what I am trying to do even if it did work, however I am struggling to think of the logic for this.
HTML:
<select id="price-from" class="form-control">
<option selected value="£500">£500</option>
<option value="1000">£1,000</option>
<option value="2000">£2,000</option>
<option value="3000">£3,000</option>
<option value="4000">£4,000</option>
<option value="5000">£5,000</option>
<option value="10000">£10,000</option>
<option value="20000">£20,000</option>
</select>
<p>To</p>
<select id="price-to" class="form-control">
<option value="500">£500</option>
<option value="1000">£1,000</option>
<option value="2000">£2,000</option>
<option value="3000">£3,000</option>
<option value="4000">£4,000</option>
<option value="5000">£5,000</option>
<option value="10000">£10,000</option>
<option selected value="20000">£20,000</option>
</select>
JavaScript:
$(document).ready(function(){
var product1 = {title:"Cute Gnome", type:"Cute", price:"3999"};
var product2 = {title:"Funny Gnome", type:"Funny", price:"5999"};
var product3 = {title:"Seasonal Gnome", type:"Seasonal", price:"12999"};
var product4 = {title:"Horror Gnome", type:"Horror", price:"7999"};
var productArray = [
product1, product2, product3, product4
];
var len = productArray.length;
for (var i = 0; i < len; i++) {
if ($("#price-from").val() < productArray[i].price && $("#price-to").val() > productArray[i].price){
//Loop through code and only output objects between both price criteria
}
}
});
You need to bind the change event to select elements. Additionally you should to convert string to Number before comparison. use .filter()
$('select').on('change', function() {
var priceFrom = +$("#price-from").val(); //Convert value to Number
var priceTo = +$("#price-to").val(); //Convert value to Number
//Filter the elements which matches the condition
var matchingElemets = productArray.filter(function(pd) {
var p = +pd.price; //Convert value to Number
return p >= priceFrom && p <= priceTo;
});
console.clear();
console.log(matchingElemets);
});
$(document).ready(function() {
var product1 = {
title: "Cute Gnome",
type: "Cute",
price: "3999"
};
var product2 = {
title: "Funny Gnome",
type: "Funny",
price: "5999"
};
var product3 = {
title: "Seasonal Gnome",
type: "Seasonal",
price: "12999"
};
var product4 = {
title: "Horror Gnome",
type: "Horror",
price: "7999"
};
var productArray = [
product1, product2, product3, product4
];
$('select').on('change', function() {
var priceFrom = +$("#price-from").val(); //Convert value to Number
var priceTo = +$("#price-to").val(); //Convert value to Number
var matchingElemets = productArray.filter(function(pd) {
var p = +pd.price; //Convert value to Number
return p >= priceFrom && p <= priceTo;
});
console.clear();
console.log(matchingElemets)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="price-from" class="form-control">
<option selected value="£500">£500</option>
<option value="1000">£1,000</option>
<option value="2000">£2,000</option>
<option value="3000">£3,000</option>
<option value="4000">£4,000</option>
<option value="5000">£5,000</option>
<option value="10000">£10,000</option>
<option value="20000">£20,000</option>
</select>
<p>To</p>
<select id="price-to" class="form-control">
<option value="500">£500</option>
<option value="1000">£1,000</option>
<option value="2000">£2,000</option>
<option value="3000">£3,000</option>
<option value="4000">£4,000</option>
<option value="5000">£5,000</option>
<option value="10000">£10,000</option>
<option selected value="20000">£20,000</option>
</select>
Code below add it to the onchange Attribute on both of the selects and you have a Framework Independent solution that Returns the list.
Ofcourse you will have to add your own logic to Change displayed products.
Do note that haveing a .ready doesnt really do annything here since it is (should be) an Event driven Action.
function filter()
{
//reduces calls to DOM in for loop
var min = document.getElementById("price-from").value;
var max = document.getElementById("price-to").value;
var length = productArray.length;
var products = [];
for (var i = 0; i < length; i++) {
if (min <= productArray[i].price && max > productArray[i].price) {
products.push(productArray[i]);
}
}
return products;
}
You presumably want to do this whenever one of the select boxes is changed, so the thing to do is hook into the change event on both and run your code. You dont specify what you mean by "output" so I'll just output to the console.
var product1 = {title:"Cute Gnome", type:"Cute", price:"3999"};
var product2 = {title:"Funny Gnome", type:"Funny", price:"5999"};
var product3 = {title:"Seasonal Gnome", type:"Seasonal", price:"12999"};
var product4 = {title:"Horror Gnome", type:"Horror", price:"7999"};
var productArray = [
product1, product2, product3, product4
];
$('select').on('change',function(){
var from = parseInt($('#price-from').val(),10);
var to = parseInt($('#price-to').val(),10);
var matches = productArray.filter(function(x){
var price = parseInt(x.price,10);
return from <= price && to >= price;
});
console.clear();
console.log(matches);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="price-from" class="form-control">
<option selected value="£500">£500</option>
<option value="1000">£1,000</option>
<option value="2000">£2,000</option>
<option value="3000">£3,000</option>
<option value="4000">£4,000</option>
<option value="5000">£5,000</option>
<option value="10000">£10,000</option>
<option value="20000">£20,000</option>
</select>
<p>To</p>
<select id="price-to" class="form-control">
<option value="500">£500</option>
<option value="1000">£1,000</option>
<option value="2000">£2,000</option>
<option value="3000">£3,000</option>
<option value="4000">£4,000</option>
<option value="5000">£5,000</option>
<option value="10000">£10,000</option>
<option selected value="20000">£20,000</option>
</select>
Roughly what this code is doing is as follows
var from = parseInt($('#price-from').val(),10);
var to = parseInt($('#price-to').val(),10);
These two lines take the values of your two select boxes, and parse their value to an integer. See parseInt
var matches = productArray.filter(function(x){
var price = parseInt(x.price,10);
return from <= price && to >= price;
});
This line uses filter to get the items from your original list which fall within the range of prices selected. See Array.filter
console.clear();
console.log(matches);
These lines simply clear and then output the items from the array which match your prices to the console. You could easily iterate over this list and output to the page iif required.
I have one select box with a list of games and the other with filled with a list of consoles. Each game has the possibility to belong to a number of consoles. I'm looking to filter the second select box according to whichever game is selected in the first.
So for instance if I select a game like Forza Horizon that belongs to more than one console then the console select box would filter just those and hide the others.
Right now I have it setup where on a select event it captures the text value of the game. From there I figured to filter through their respective optgroup's label property, which is the console it belongs to. I just can't seem to figure out how to retrieve the other possible consoles it may belong to other than the selected option.
Fiddle
<select class="game-select">
<option value="">Select a game</option>
<optgroup label="PS4"></optgroup>
<option value="1">Forza Horizon 2</option>
<option value="2">The Last of Us</option>
<option value="3">Bioshock Infinite</option>
</optgroup>
<optgroup label="Xbox One">
<option value="1">Forza Horizon</option>
<option value="2">Halo</option>
<option value="3">Bioshock Infinite</option>
</optgroup>
</select>
<select class="console-select">
<option value="">Select a console</option>
<option value="1">PS4</option>
<option value="2">Xbox One</option>
</select>
JS
$(function() {
var gameConsoles = $(".console-select").html();
$(".game-select").on("change", function() {
var game = $(this).find("option:selected").text(),
options = gameConsoles.filter().html(); // Not sure how to filter
if (options) {
$(".console-select").html(options);
} else {
$(".console-select").empty();
}
});
});
Update 2
You can do something like this
$(function () {
var consoleSelect = $('.console-select'),
gameConsoleOptions = $('.console-select option');
$(".game-select").on("change", function () {
var selectedGame = $(this).find("option:selected").data('game'),
games = [],
selectedCategory = $(this).find("option:selected").closest('optgroup').attr('label');
if (selectedGame) {
games = $.makeArray($(this).find('option[data-game="' + selectedGame + '"]').map(function () {
return $(this).closest('optgroup').attr('label');
}));
}
if (games.length) {
gameConsoleOptions.hide();
gameConsoleOptions.filter(function (i, v) {
return games.indexOf($(v).text()) != -1;
}).show();
consoleSelect.find('option:contains('+selectedCategory+')').prop('selected', 'selected');
} else {
gameConsoleOptions.show();
}
});
});
Here is a demo http://jsfiddle.net/dhirajbodicherla/m178xpc3/11/
Update
I added a code to each game using the data-* attribute.
For example the below two games have the same data-game attribute which can be used to figure out that these two are of the same category.
<option value="1" data-game="FH">Forza Horizon 2</option>
<option value="2" data-game="FH">Forza Horizon</option>
Complete example
<select class="game-select">
<option value="">Select a game</option>
<optgroup label="PS4">
<option value="1" data-game="FH">Forza Horizon 2</option>
<option value="2" data-game="LU">The Last of Us</option>
<option value="3" data-game="BI">Bioshock Infinite</option>
</optgroup>
<optgroup label="Xbox One">
<option value="1" data-game="FH">Forza Horizon</option>
<option value="2" data-game="HA">Halo</option>
<option value="3" data-game="BI">Bioshock Infinite</option>
</optgroup>
</select>
<select class="console-select">
<option value="">Select a console</option>
<option value="1">PS4</option>
<option value="2">Xbox One</option>
</select>
This is the script
$(function () {
var gameConsoleOptions = $('.console-select option');
$(".game-select").on("change", function () {
var selectedGame = $(this).find("option:selected").data('game'), games = [];
console.log(selectedGame);
if (selectedGame) {
games = $.makeArray($(this).find('option[data-game="' + selectedGame + '"]').map(function () {
return $(this).closest('optgroup').attr('label');
}));
}
console.log(games);
if (games) {
gameConsoleOptions.hide();
gameConsoleOptions.filter(function (i, v) {
return games.indexOf($(v).text()) != -1;
}).show();
} else {
gameConsoleOptions.show();
}
});
});
Here is a demo http://jsfiddle.net/dhirajbodicherla/m178xpc3/10/
You can do something like this
$(function () {
var gameConsoleOptions = $('.console-select option');
$(".game-select").on("change", function () {
var label = $(this).find("option:selected").closest('optgroup').prop('label');
if (label) {
gameConsoleOptions.hide();
gameConsoleOptions.filter(function (i, v) {
return $(v).text() === label;
}).show();
}else{
gameConsoleOptions.show();
}
});
});
Here is a demo http://jsfiddle.net/dhirajbodicherla/m178xpc3/5/
The code should speak for itself but it all comes down to multiple jQuery filter functions and a clone of the set with options. One advice: Use data attributes instead of relying on the option element text. I updated the fiddle, see link below.
$(function() {
var gameConsoles = $(".console-select");
var consoleOptions = gameConsoles.find('option').clone();
var gameSelect = $(".game-select").on("change", function() {
var game = $(this).find("option:selected").text();
var filteredOptions = $();
gameSelect.find('optgroup').filter(function() {
return $(this).find('option').filter(function() {
return $(this).text() == game;
}).length;
}).each(function () {
var label = $(this).attr('label');
filteredOptions = filteredOptions.add(consoleOptions.filter(function() {
return $(this).text() == label;
}));
});
gameConsoles.html(filteredOptions);
});
});
Fiddle update
Is that what you wanted?
$(".game-select").on("change", function() {
var o = $('option:selected', $(this));
if (!o.val()) {
$('.game-select optgroup').show();
$('.console-select option').show();
return;
}
$('.console-select > option').hide();
var a = $('option:contains("' + o.text() + '")').filter(function() {
return $(this).text() == o.text();
}).each(function() {
var t = $(this);
var l = t.parent().attr('label');
$('.console-select option:contains("' + l + '")').filter(function() {
return l == $(this).text();
}).show();
});
});
$(".console-select").on("change", function() {
var o = $('option:selected', $(this));
if (!o.val()) {
$('.game-select optgroup').show();
$('.console-select option').show();
return;
}
$('.game-select optgroup').hide();
console.log($('.game-select optgroup[label="' + o.text() + '"]'));
$('.game-select optgroup[label="' + o.text() + '"]').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="game-select">
<option value="">Select a game</option>
<optgroup label="PS4">
<option value="c1">Forza Horizon 2</option>
<option value="c2">The Last of Us</option>
<option value="c3">Bioshock Infinite</option>
</optgroup>
<optgroup label="Xbox One">
<option value="s1">Forza Horizon</option>
<option value="s2">Halo</option>
<option value="s3">Bioshock Infinite</option>
</optgroup>
</select>
<select class="console-select">
<option value="">Select a console</option>
<div>
<option value="c">PS4</option>
<option value="s">Xbox One</option>
</div>
</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;
}