I have 2 drop down lists , and value of the second drop down list should change according to the value selected in first drop down list. The current drop down lists are.
<select name="first">
<option name="a" value="a">a</option>
<option name="b" value="b">b</option>
<option name="c" value="c">c</option>
</select>
<select name="second">
<option name="a1" value="a1">a1</option>
<option name="a2" value="a2">a2</option>
<option name="b1" value="b1">b1</option>
<option name="b2" value="b2">b2</option>
<option name="c1" value="c1">c1</option>
<option name="c2" value="c2">c2</option>
</select>
I want the second drop down to be displayed according to the value selected in First dropdown, ie, if "a" is selected in first then only a1 and a2 should be shown. Also drop down values are pulled from a database
Thanks
There are just limited options to do so
OnChange event
Classic html/javascript/post refresh
One option is to load everything you have in the database in a standard form such as JSON. Then, you'd have to write javascript to build the dropdowns dynamically as the user interacts with each item.
Here is an example of how you'd go about doing it http://jsfiddle.net/9Z5t8/1/
There are some drawbacks. If you have a LOT of data (hundreds of records) to transfer this will be slow, but it's okay for a few records.
You can save the options in a separate array, and insert the appropriate ones when a value is selected: http://jsfiddle.net/KTQ7d/.
var arr = [];
var first_select = document.getElementsByTagName('select')[0]
var second_select = document.getElementsByTagName('select')[1]
var elems = second_select.getElementsByTagName('option');
for(var i = 0; i < elems.length; i++) {
arr.push(elems[i].value);
}
first_select.onchange = function() {
second_select.innerHTML = '';
for(var i = 0; i < arr.length; i++) {
if(arr[i][0]
==
first_select.options[first_select.selectedIndex].value) {
var opt = document.createElement('option');
opt.name = arr[i];
opt.value = arr[i];
opt.innerHTML = arr[i];
second_select.appendChild(opt);
}
}
};
Related
I have select with this options:
<select name="kategory" class="select-field">
<option disabled>ATRACTIONS
<option value="">
<option value="Castles">Castles
<option value="History">History
</select>
And I have a chceck box:
Do you want to eat?<input type="checkbox" class="checkbox" name="restaurants" value="" />
after I click in chceckbox for true I need change the select option values to :
<option disabled>Restaurants
<option value="China food">Chinas food
<option value="Pizza">Pizza
<option value="Pub">Pub
but with no need to refresh page. How can I do that? thanks
I would use javascript or jquery whatever you are more comfortable with. Haven't tried this but something like this should work.
HTML:
<select name="kategory" class="select-field">
<option disabled>ATRACTIONS
<option value="">
<option value="Castles">Castles
<option value="History">History
</select>
<br>
<span>Do you want to eat?</span>
<input type="checkbox" class="checkbox" name="restaurants" value="" onchange="changeSelect()"/>
JQUERY:
// options
var myOptions = {
val1 : 'Chinese food',
val2 : 'Pizza',
val3 : 'Pub'
};
var mySelect = $('.select-field');
function changeSelect(element){
if (element.checked){
$.each(myOptions, function(val, text) {
mySelect.append(
$('<option></option>').val(val).html(text)
);
});
} else {
return;
}
};
If you do not want to refresh the page, you will want to look into using perhaps Javascript/jQuery. These are great tools for what you are looking for (IMO).
You will be able to reference your dropdown 'kategory' and update the options after checking the checkbox.
If that's the route you would like to go and are not sure how to do so, let us know and we can include examples.
Edit: unsalted has the right idea using objects. If you want another option that just empties the select and builds the html directly here is another way using jQuery.
$('input[name="restaurants"]').change(function(){
if( this.checked )
{
var select = $('select[name="kategory"]');
select.empty();
var options = '';
options += '<option disabled>Restaurants</option>';
options += '<option value="China food">Chinas food</option>';
options += '<option value="Pizza">Pizza</option>';
options += '<option value="Pub">Pub</option>';
select.html(options);
}
});
I'm trying to store variables from select/option, and then access them from a button to send to a javascript function that would filter some divs on my page.
So far I have it sending the value to "filter()" when the value changes.
Here's my markup:
<select name="Area" onchange="filter(this)">
<option selected>Select</option>
<option value="Austin">Austin</option>
<option value="San Antonio">San Antonio</option>
<option value="Temple">Temple</option>
</select>
<select name="Number" onchange="filter(this)">
<option selected>Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<a class="button">Submit</a>
but how do I store the values from all the options, and then send them
all at once to the function?
Edit: In other words, how do I store the value of each option, and only send to the function once they click submit?
If I got it right, without jQuery you may try this:
document.getElementById("button").onclick = function() {
var selects = document.body.getElementsByTagName("select");
var data = [];
for (var i = 0; i < selects.length; i++) {
data.push(selects[i].value);
}
destinyFunction(data);
};
Or you may use jQuery for the sake of simplicity:
$("#jbutton").on("click", function() {
var data = [];
$("select").each(function() {
data.push($(this).val());
});
destinyFunction(data);
});
Fiddle with those two examples here.
Give each of your selects an id attribute, like:
<select name="Number" onchange="filter(this)" id="Number">
...
Then you can get the value of each in javascript by:
var el = document.getElementById('Number');
var value = el.options[el.selectedIndex].value;
As a sidenote, using onchange in HTML markup to attach your event handling is not best practice. This article from quirksmode offers a good explanation of alternative solutions. However, there are major cross-browser considerations to be taken into account, which is why most people prefer to use a Javascript framework so that those are mostly mitigated.
I have a date SELECT/OPTION create by JS.
The code works fine, but when this file post to different page. The SELECT didn't retain the value when I click back button from browser or when I post it back. The day and year become blank. Copy the code and try it in your browser you will understand what I mean.
Any suggestion?
<script>
function populate(s1, s2){
var s1=document.getElementById(s1);
var s2=document.getElementById(s2);
s2.innerHTML="";
if(s1.value==""){
var optionArray=['|Day'];
}
else if(s1.value=="01" || s1.value=="03" || s1.value=="05" || s1.value=="07" || s1.value=="08" || s1.value=="10" || s1.value=="12"){
var optionArray=['|Day'<?PHP for($d=1; $d<32; $d++){echo ", '$d|$d'";}?>];
}
else if(s1.value=="04" || s1.value=="06" || s1.value=="09" || s1.value=="11"){
var optionArray=['|Day'<?PHP for($d=1; $d<31; $d++){echo ", '$d|$d'";};?>];
}
else if(s1.value=="02"){
var optionArray=['|Day'<?PHP for($d=1; $d<30; $d++){echo ", '$d|$d'";};?>];
}
for(var option in optionArray){
var pair=optionArray[option].split("|");
var newOption=document.createElement("option");
newOption.value=pair[0];
newOption.innerHTML=pair[1];
s2.options.add(newOption);
}
}
function populate_year(s2, s3){
var s2=document.getElementById(s2);
var s3=document.getElementById(s3);
s3.innerHTML="";
if(s2.value==""){
var optionArray=['|Year'];
}
else if(s2.value=="29"){
var optionArray=['|Year'<?PHP for($y=1936; $y<2013; $y=$y+4){echo ", '$y|$y'";};?>];
}
else if(s2.value!=="29"){
var optionArray=['|Year'<?PHP for($y=1933; $y<2013; $y++){echo ", '$y|$y'";};?>];
}
for(var option in optionArray){
var pair=optionArray[option].split("|");
var newOption=document.createElement("option");
newOption.value=pair[0];
newOption.innerHTML=pair[1];
s3.options.add(newOption);
}
}
</script>
<select id="s1" onchange="populate(this.id, 's2')" name="month" style="width:80px; font-family:arial;">
<option value="">Month</option>
<option value="01">Jan</option>
<option value="02">Feb</option>
<option value="03">Mar</option>
<option value="04">Apr</option>
<option value="05">May</option>
<option value="06">Jun</option>
<option value="07">Jul</option>
<option value="08">Aug</option>
<option value="09">Sep</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
<select id="s2" onchange="populate_year(this.id, 's3')" name="day" style="width:65px; font-family:arial;">
<option value="">Day</option>
</select>
<select id="s3" name="Year" style="width:80px; font-family:arial;">
<option value="">Year</option>
</select>
The issue is the html for the day and year are dynamically generated, so the value of the last selected index can't be injected into the select boxes (because the select boxes haven't been made yet).
I have two suggestions:
1) I wouldn't populate each select option dynamically. Perhaps have 3 select boxes in the DOM for each of the three different types of day selections (30 days, 31 days, and for February). The JavaScript that executes when selecting a month doesn't populate the select box, but shows the appropriate select box for days and hides the other two. By default, they would all be hidden. You would then repeat something similar for the year select box.
2) If you must dynamically generate your content, I would attempt storing the selected index in Local Storage (or whatever other means tickles your fancy). For example, if someone selects January, 23, 2012.. store this in Local Storage. This could look something like this:
localStorage['dateSelect'] = '01|23|2012';
This is just an example of what you could do. Then, you could read from it upon page load.
var selectedMonth;
var selectedDay;
var selectedYear;
if (localStorage['dateSelect']) {
var storage = localStorage['dateSelect'].split('|');
selectedMonth = storage[0];
selectedDay = storage[1];
selectedYear = storage[2];
}
Let me know if you need any more help :)
Good luck!
-Graham
I do have this script to generate three dropdowns and one text input field for my webform that i have to submit to a database using PHP. This form is HTML but only this part is javascript to populate the fields. I am using this javascript to generate approx 15 sets of these dropdowns and text input fields. (1 set = 3 dropdowns and 1 input text field).
My question is : If user selects an option from first dropdown then the options in the other two dropdowns should change according to the selected option in the first drodown.
What I wanted to is after generating the desired number of sets by selecting the number from the dropdown in this fiddle, it will generate sets od 3 dropdowns and 1 input field dynamically.
So if someone selects option one from the first dropdown it should change the options in the other dropdowns as well.
JSFIDDLE
THE SCRIPT:
<script>
$(function() {
$("input[type=button][value=Add]").click(function(e) {
for (i = 0; i < document.getElementById('sel').value; i++) {
e.preventDefault();
var j = 1;
var newDiv = $("<div>").appendTo("#dropbox");
$("<select>").attr("name", "input1_"+j).appendTo(newDiv).append(
$("<option>").val("0").text("Option 1"), $("<option>").val("1").text("Option 2"));
$("<select>").attr("name", "input2_"+j).appendTo(newDiv).append(
$("<option>").val("0").text("Option 1"), $("<option>").val("1").text("Option 2"));
$("<select>").attr("name", "input3_"+j).appendTo(newDiv).append(
$("<option>").val("0").text("Option 1"), $("<option>").val("1").text("Option 2"));
$("<input>").attr("name", "input4_"+j).appendTo(newDiv);
$("<button>").text("Remove").appendTo(newDiv).click(function(e) {
e.preventDefault();
$(this).parent().remove();
})
j++;
}
})
})
</script>
THE HTML:
<form>
<select id="sel">
<option value="" selected="selected"></option>
<option value="01" >01</option>
<option value="02" >02</option>
<option value="03" >03</option>
<option value="04" >04</option>
<option value="05" >05</option>
<option value="06" >06</option>
<option value="07" >07</option>
<option value="08" >08</option>
<option value="09" >09</option>
<option value="10" >10</option>
<option value="11" >11</option>
<option value="12" >12</option>
<option value="13" >13</option>
<option value="14" >14</option>
<option value="15" >15</option>
</select>
<input type="button" value="Add" />
<div id="dropbox"></div>
</form>
Since you use jQuery, I suggest to add a change event to your dropdown. (The linked jQuery docs page contains a full example).
Regarding filling the other 2 drop-downs, you have several options, such as:
Static: Your PHP code that creates the page fills in a javascript array with all possible options needed according to user choice in the 1st dropdown. Then your javascript code can use this array whenever a change event is triggered.
Dynamic: If sub-choices can't be predicted or loaded at page load, use a jQuery ajax request to query the server for options matching user choice. You may also want to read about the JSon data format (supported by PHP using json_encode)
DEMO
I gave the sel and the button an ID and changed the dom access to jQuery
I also use the "i" and "j" now
Assuming you wanted to syncronise the 3 selects, the code could look like this
$(function() {
$("input[type=button][value=Add]").click(function(e) {
e.preventDefault();
for (var i=0,n=$('#sel').val();i<n; i++) {
var newDiv = $("<div>").appendTo("#dropbox");
for (var j=0;j<3;j++) {
var id = "input"+i+"_"+j;
$("<select>")
.attr("id",id)
.attr("name",id)
.on("change",function() {
// set all other select's value to this value
$(this).siblings("select").val(this.value);
})
.append(
$("<option>").val("0").text("Option 1"),
$("<option>").val("1").text("Option 2"))
.appendTo(newDiv);
} // j
$("<input>")
.attr("name", "input"+i+"_"+j)
.appendTo(newDiv);
$("<button>").text("Remove").appendTo(newDiv).click(function(e) {
e.preventDefault();
$(this).parent().remove();
})
} // i
})
})
I have been searching for similar questions but they are a little different to what I am looking for.
Basically, this is what I am aiming to implement:
Have a first drop-down list filled with values, e.g. :
<form>
<select id="tags" name="tags">
<option value="agent" selected="selected">agent</option>
<option value="extension">extension</option>
<option value="fileversion" >fileversion</option>
<option value="pages">pages</option>
</select>
Then, in a second drop-down list, show options dependant on what was selected, for example, if agent is selected, the operators would be = or != since it is text. For fileversion there would be 4 operands, =, !=, > and <.
Lastly, there would be a third drop-down with values also dependant on the initially selected option.
For example, when agent is selected, the options would be pdf, word, excel, ppt etc. and others it would just be a text box to type in rather than exhaust all possible values.
In the end this will be used to search a database but it is a big db and the searches are too slow so I'm thinking the values for the options will be stored in an array rather than pulled directly.
As you can see, it's fairly tricky :/ any help at all is much appreciated.
Thanks,
Martin
EDIT:
Found the answer for those who happen to be looking for the same answer:
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
<script type="text/javascript" src="js/dropdown.js"></script>
</head>
<body>
<form>
<select id="tags" name="tags">
<option value="tags" selected="selected">tags</option>
<option value="agent">agent</option>
<option value="extension">extension</option>
</select>
<select name="operands">
<option>operands</option>
</select>
</form>
</body>
</html>
dropdown.js:
$(document).ready(function() {
$tags = $("select[name='tags']");
$operands = $("select[name='operands']");
$tags.change(function() {
if ($(this).val() == "agent") {
$("select[name='operands'] option").remove();
$("<option>=</option>").appendTo($operands);
$("<option>!=</option>").appendTo($operands);
}
if ($(this).val() == "extension")
{
$("select[name='operands'] option").remove();
$("<option>.pdf</option>").appendTo($operands);
$("<option>.doc</option>").appendTo($operands);
}
if ($(this).val() == "tags")
{
$("select[name='operands'] option").remove();
$("<option>operands</option>").appendTo($operands);
}
});
});
try something like this, a data object filled with the corresponding data..
var data = {
agent: [
["=", "!="], //values that are shown in 1st dropdown when agent is selected
["a", "b"] //values that are shown in 2nd dropdown when agent is selected
]
extension: [
["pdf", "doc"], //values that are shown in 1st dropdown when extension is selected
["c", "d"] //values that are shown in 2nd dropdown when extension is selected
]
}
and for the HTML
<select id="tags" name="tags">
<option value="agent" selected="selected">agent</option>
<option value="extension">extension</option>
<option value="fileversion" >fileversion</option>
<option value="pages">pages</option>
</select>
<select id="dropdown2" name="dropdown2">
</select>
<select id="dropdown3" name="dropdown3">
</select>
Now listen for changes on the tags dropdown and get the options from the data object (example using jquery)
$("#tags").change(function() {
setDropDown1(data[$(this).val()][0]);
setDropDown2(data[$(this).val()][1]);
});
pass the data to a function like this to create the dropdown options
function setDropDown1(data) {
$("#dropdown1").html(""); //clear options
for (var i = 0; i < data.length; i++) {
$("#dropdown1").append("<option value='" + data[i] + "'>" + data[i] + "</option>");
}
}
var selectionObject = {
agent = ["=","!="],
fileversion = ["=","!=",">","<"],
...
}
$('form select#tags').click(function(){
comboBoxSelection = $(this).val();
secondDropDownvalues = selectionObject[comboBoxSelection];
....
});
In pseudo code should be something like that