Is there a way to select all option values in selectbox? - javascript

I have a function that creates many select boxes. I need an option value to select all the values in one select, because if I give "all" as value, I have to do a lot of switches and if / else statements, and it would be great if I could avoid that.
Here is the function:
function creaselect(nomeoggetto, oggetto, nome) {
var P_P_comodo = _(A_Punti_dati).groupBy(oggetto).map(function(item, itemId) {
console.log(oggetto);
var result = {};
result[itemId] = item[0][nome];
return result
}).value();
document.write("Seleziona " + nomeoggetto + "<select id=my" + nomeoggetto + ">");
document.write("<option value=all selected>Tutti</option>");
_.each(P_P_comodo, function(value, key) {
_.each(value, function(value, key) {
P_P[key] = value;
document.write("<option value=" + key + ">" + value + "</option>");
});
});
document.write("</select><br>");
}

You'll need to do 2 things:
Set up a function to iterate through each option and set the "selected" attribute to true
Set up a handler to call this function when the user selects "all"
HTML
<select id='control'>
<option value=''>(Select one)</option>
<option value='all'>All</option>
<option value='none'>None</option>
</select>
<select id='sel' name="sometext" size='5' multiple>
<option value='1'>text1</option>
<option value='2'>text2</option>
<option value='3'>text3</option>
<option value='4'>text4</option>
<option value='5'>text5</option>
</select>
Javascript
var control = document.getElementById('control');
control.onchange = setOptions;
function setOptions() {
var control = document.getElementById('control');
var val = control.value;
if (val == 'all' || val == 'none') {
var mySelectObj = document.getElementById('sel');
var bool = val == 'all'
setSelect(mySelectObj, bool);
}
}
function setSelect(sel, bool){
for(var i = 0; i <sel.length; i++) {
sel.options[i].selected = bool;
}
}
jsFiddle: https://jsfiddle.net/mspinks/qqp7w1qk/11/
Please note: in order to allow multi-select on a select input, you must specify the attribute "multiple". Otherwise, you'll need to use a third-party select control.

Related

Append options to select box depend on extracted part from array

I have 4 selectboxs moduleName, submoduleName, ProgrameName and last selectbox has all data for username, module, submodule and programe name merged and splited with ";" between each other, I need: when user select module name from moduleName Selectbox it filters values in all data selectbox and splites submoduleNames under this moduleName and append it as options to submoduleName Selectbox, also the same when user select from submoduleName selectbox it filters programeNames under this module and subModuleNames and append it as options in programeName selectbox. I tried to splite each line in allData selectbox but i failed to continue. here what i tried but it is not working.
Thank you for your help.
$(document).ready(function(){
function check(){
var lines = $('#splitedOptions').val().split(/\n/);
var texts = [];
for (var i=1; i < lines.length; i++) {
texts.push(lines[i]);
}
for (var i=0; i < texts.length; i++) {
var extractedPart = texts[i].split(';'),
ModuleNameVal = $("#moduleName option:selected").val();
if(extractedPart[1] == ModuleNameVal){
var newOption = "<option value='"+extractedPart[2]+"'>"+extractedPart[2]+"</option>";
$('#SubModuleName').append(newOption);
}
}
}
function c1() {
var optionsCount = $('#allData').find('option').size();
var textArea ="";
for (var i = 1; i <= optionsCount; i++) {
if(i!=1){
textArea += '\n';
}
var xItem = $('#allData').find('option:nth-child(' + (i) + ')').text();
textArea += xItem ;
}
$('#splitedOptions').val('');
$('#splitedOptions').val(textArea);
check();
}
$('#moduleName').change(function(){
c1()
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>ModuleName:</label>
<select class="moduleName" id="moduleName">
<option value="HR">HR</option>
<option value="Marketing">Marketing</option>
<option value="Purchase">Purchase</option>
<option value="Finance">Finance</option>
</select><br><br>
<label>SubModuleName:</label>
<select class="SubModuleName" id="SubModuleName"></select><br><br>
<label>ProgrameName:</label>
<select class="programeName" id="programeName"></select><br><br>
<label>All Data:</label>
<select class="allData" id="allData">
<option value="userName;HR;Transactions;EmployeeMaster">Option1</option>
<option value="userName;HR;Master;EmployeeMaster">Option2</option>
<option value="userName;Marketing;Master;MarketingMaster">Option3</option>
<option value="userName;HR;Reports;HRReports">Option4</option>
<option value="userName;Purchase;PurchaseOrders;LPO">Option5</option>
<option value="userName;Purchase;PurchaseOrders;IPO">Option6
<option value="userName;Finance;Master;FinanceMasterPrograme">Option7</option>
<option value="userName;Finance;Reports;FinanceReportsPrograme">Option8</option>
</select><br><br>
<label>splited Options:</label>
<textarea id="splitedOptions" name="splitedOptions" ></textarea>
One way to achieve above is to filter the options from allData select-box and get only those option which has the value which user has selected using value*="yourvalue".
Then , onces you get the options you need to know which select-box has been change so that we can get required value only when we do split and pass required index .
Lastly , we need to loop through the options which we have got from filtering select-box .Suppose user select Master so there are Master in many places so to avoid getting data from all option i have check the value of select with the first select-box as well if matches apppend only those options.
Demo Code :
$('select').change(function() {
//get value
var name = $(this).val();
//filter option and get only option which has the value which user has slected
var s = $("#allData").find('option').filter('[value*=' + name + ']').each(function(ele) {
return $(this).val();
});
var module_namess;
var index;
//check the id of select-box
if ($(this).attr("id") == "moduleName") {
module_namess = "SubModuleName";
index = 2;//set index
} else if ($(this).attr("id") == "SubModuleName") {
name = $("#moduleName").val()
module_namess = "programeName"
index = 3
}
$("#" + module_namess).empty()
$('#' + module_namess).append("<option >Select one</option>")
var valuess = ''
//loop through options
for (var i = 0; i < s.length; i++) {
valuess += $(s[i]).val()
//if first value is same
if ($(s[i]).val().split(";")[1] == name) {
var sub_value = $(s[i]).val().split(";")[index]//get the value
var newOption = "<option value='" + sub_value + "'>" + sub_value + "</option>";
$('#' + module_namess).append(newOption);//append
}
}
$('#splitedOptions').val(valuess);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>ModuleName:</label>
<select class="moduleName" id="moduleName">
<option value="HR">HR</option>
<option value="Marketing">Marketing</option>
<option value="Purchase">Purchase</option>
<option value="Finance">Finance</option>
</select><br><br>
<label>SubModuleName:</label>
<select class="SubModuleName" id="SubModuleName"></select><br><br>
<label>ProgrameName:</label>
<select class="programeName" id="programeName"></select><br><br>
<label>All Data:</label>
<select class="allData" id="allData">
<option value="userName;HR;Transactions;EmployeeMaster">Option1</option>
<option value="userName;HR;Master;EmployeeMaster">Option2</option>
<option value="userName;Marketing;Master;MarketingMaster">Option3</option>
<option value="userName;HR;Reports;HRReports">Option4</option>
<option value="userName;Purchase;PurchaseOrders;LPO">Option5</option>
<option value="userName;Purchase;PurchaseOrders;IPO">Option6
<option value="userName;Finance;Master;FinanceMasterPrograme">Option7</option>
<option value="userName;Finance;Reports;FinanceReportsPrograme">Option8</option>
</select><br><br>
<label>splited Options:</label>
<textarea id="splitedOptions" name="splitedOptions"></textarea>

How can I set the default value for a dropdown selection

I assumed that the my select state dropdown box would automatically display "select state" However, this did not work as I had expected. The dropdown box is empty until I choose a country and only then will the state dropdown box display "select state. How can I set my state dropdown box to "select state" by default?
function populateStates(countryElementId, stateElementId) {
var selectedCountryIndex = document.getElementById(countryElementId).selectedIndex;
var stateElement = document.getElementById(stateElementId);
stateElement.length = 0; //
stateElement.options[0] = new Option('Select State', '');
stateElement.selectedIndex = 0;
var state_arr = s_a[selectedCountryIndex].split("|");
for (var i = 0; i < state_arr.length; i++) {
if (state_arr[i] != "") {
stateElement.options[stateElement.length] = new Option(state_arr[i], state_arr[i]);
}
}
}
function populateCountries(countryElementId, stateElementId) {
// given the id of the <select> tag as function argument, it inserts <option> tags
var countryElement = document.getElementById(countryElementId);
jQuery("#" + countryElementId + " option").remove();
jQuery("#" + countryElementId).append("<option value=\"\">USA</option>");
for (var i = 0; i < country_arr.length; i++) {
countryElement.options[countryElement.length] = new Option(country_arr[i], country_arr[i]);
}
// Assigned all countries. Now assign event listener for the states.
if (stateElementId) {
countryElement.onchange = function() {
populateStates(countryElementId, stateElementId);
jQuery("#" + stateElementId + " option:eq(0)").attr("selected", "selected");
jQuery("#" + stateElementId).val("").change();
if (jQuery("#" + countryElementId).val() == "USA") {
jQuery("#Zip_Postal_Code__c").attr("maxlength", "5");
} else if (jQuery("#" + countryElementId).val() == "Canada") {
jQuery("#Zip_Postal_Code__c").attr("maxlength", "6");
} else {
jQuery("#Zip_Postal_Code__c").removeAttr("maxlength");
}
};
}
}
You can just use the default state dropdown html to contain only one option: Select State. e.g. in the html
<select id="state_select">
<option value="">Select State</option>
</select>
To prevent the first option from being selected:
<select>
<option value="" disabled selected hidden>Select State</option>
<option value="USA">USA</option>
<option value="Canada">Canada</option>
</select>

Count Unique Selection from Multiple Dropdown

I'm new to jquery, I'm working on a survey form and I have multiple dropdown menus for different questions but they all have the same dropdown value. Supposed I have:
<select name="Forms[AgentIsPitch]" id="Forms_AgentIsPitch">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<select name="Forms[MandatoryOptIsStated]" id="Forms_MandatoryOptIsStated">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
And other different dropdowns with different id's. What is the best way to count how many has selected Yes, No and N/A/ ? Thanks
you can do it simple this way
$('select').change(function() {
// get all selects
var allSelects = $('select');
// set values count by type
var yes = 0;
var no = 0;
// for each select increase count
$.each(allSelects, function(i, s) {
// increase count
if($(s).val() == 'Yes') { yes++; }
if($(s).val() == 'No') { no++; }
});
// update count values summary
$('.cnt-yes').text(yes);
$('.cnt-no').text(no);
});
DEMO
Try this — https://jsfiddle.net/sergdenisov/h8sLxw6y/2/:
var count = {};
count.empty = $('select option:selected[value=""]').length;
count.yes = $('select option:selected[value="Yes"]').length;
count.no = $('select option:selected[value="No"]').length;
count.nA = $('select option:selected[value="N/A"]').length;
console.log(count);
My way to do it would be :
var optionsYes = $("option[value$='Yes']:selected");
var optionsNo = $("option[value$='No']:selected");
var optionsNA = $("option[value$='N/A']:selected");
console.log('number of yes selected = ' + optionsYes .length);
console.log('number of no selected = ' + optionsNo .length);
console.log('number of N/A selected = ' + optionsNA .length);
Check the console (or replace with alert).
With your code, it would be something like that (assuming you want to check on a button click event) :
<select name="Forms[AgentIsPitch]" id="Forms_AgentIsPitch">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<select name="Forms[MandatoryOptIsStated]" id="Forms_MandatoryOptIsStated">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<button class="btn btn-primary" id="countYes"></button>
<script type="text/javascript">
$('#countYes').on('click', function(){
var optionsYes = $("option[value$='Yes']:selected");
var optionsNo = $("option[value$='No']:selected");
var optionsNA = $("option[value$='N/A']:selected");
console.log('number of yes selected = ' + optionsYes .length);
console.log('number of no selected = ' + optionsNo .length);
console.log('number of N/A selected = ' + optionsNA .length);
});
</script>
You can check at another event, I choosed a button click just for example.
There is likely a cleaner way to do this, but this will get the job done (assuming there is a button click to trigger things):
$("#theButton").on('click', function() {
var totalSelect = 0;
var totalYes = 0;
var totalNo = 0;
var totalNA = 0;
$("select").each(function(){
totalSelect++;
if ($(this).val() == "Yes") { totalYes++; }
if ($(this).val() == "No") { totalNo++; }
if ($(this).val() == "N/A") { totalNA++; }
});
});
Hope this helps the cause.
In common you can use change event:
var results = {};
$('select').on('change', function() {
var val = $(this).val();
results[val] = (results[val] || 0) + 1;
});
DEMO
If you want count for each type of select:
$('select').on('change', function() {
var val = $(this).val();
var name = $(this).attr('name');
if (!results[name]) {
results[name] = {};
}
results[name][val] = (results[name][val] || 0) + 1;
});
DEMO
In the results will be something like this:
{
"Forms[AgentIsPitch]": {
"Yes": 1,
"No": 2,
"N/A": 3
},
"Forms[MandatoryOptIsStated]": {
"No": 5,
"N/A": 13
},
}
UPD: for counting current choice:
$('select').on('change', function() {
var results = {};
$('select').each(function() {
var val = $(this).val();
if (val) {
results[val] = (results[val] || 0) + 1;
}
})
console.log(results);
});
DEMO

reset a drop down list value to previous value

I am using javascript to validate some drop down list selections. One selection is for the length of a buildings frame. The other 3 drop down are for garage doors that can be added to the side. I have the code alerting me if the total door widths have exceeded the frame length. I need the if condition to take the previous value of the last selected door drop down list and reset it to the amount before it if the amount exceeds my conditions in my if statement.
This is my html
Frame Length:
<select id="framewidth" onchange="doorsrightsideFunction()">
<option value="20">21</option>
<option value="25">26</option>
<option value="30">31</option>
<option value="35">36</option>
<option value="40">41</option>
</select>
<br>
<input type="hidden" name="eight_by_seven_width_right_side"
id="eight_by_seven_width_right_side" value="8">
<br>
<input type="hidden" name="eight_by_seven_height_right_side"
id="eight_by_seven_height_right_side" value="7">
<br>8x7:
<select id="eight_by_seven_right_side" onchange="doorsrightsideFunction()">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br>
<input type="hidden" name="nine_by_seven_width_right_side"
id="nine_by_seven_width_right_side" value="9">
<br>
<input type="hidden" name="nine_by_seven_height_right_side"
id="nine_by_seven_height_right_side" value="7">
<br>9x7:
<select id="nine_by_seven_right_side" onchange="doorsrightsideFunction()">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br>
<input type="hidden" name="ten_by_eight_width_right_side"
id="ten_by_eight_width_right_side" value="10">
<br>
<input type="hidden" name="ten_by_eight_height_right_side"
id="ten_by_eight_height_right_side" value="8">
<br>10x8:
<select id="ten_by_eight_right_side" onchange="doorsrightsideFunction()">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
This is my javascript so far
function doorsrightsideFunction() {
function getValue(idElement) {
return document.getElementById(idElement).value;
}
var eightwidth = getValue("eight_by_seven_width_right_side");
var ninewidth = getValue("nine_by_seven_width_right_side");
var tenwidth = getValue("ten_by_eight_width_right_side");
var eightwidthamount = getValue("eight_by_seven_right_side");
var ninewidthamount = getValue("nine_by_seven_right_side");
var tenwidthamount = getValue("ten_by_eight_right_side");
var framewidth = getValue("framewidth");
var totaldoorwidth;
var totaldooramount;
var framewidthtotaldoorwidth;
var framespace;
totaldoorwidth = eightwidth * eightwidthamount
+ ninewidth * ninewidthamount
+ tenwidth * tenwidthamount;
totaldooramount = parseInt(eightwidthamount, 10)
+ parseInt(ninewidthamount, 10)
+ parseInt(tenwidthamount, 10);
framewidthtotaldoorwidth = framewidth - totaldoorwidth;
framespace = totaldooramount + 1;
if (framewidthtotaldoorwidth < framespace) {
alert("You have to many doors on the right side");
} else { }
}
here is a link to my fiddle http://jsfiddle.net/steven27030/M52Hf/
http://jsfiddle.net/M52Hf/84/
you could use the data attribute and be sure to pass in the current element as a parameter on your doorsrightsideFunction call:
<select id="framewidth" onchange="doorsrightsideFunction(this)">
var previousValue = currentelement.getAttribute("data-prev");
if(previousValue == null)
previousValue = currentelement[0].value;
You will need to store the previous value so you can switch back when necessary, and update the previous value after a successful change. I would use arrays in various places.
var prevValue = Array();
function doorsrightsideFunction() {
function getValue(idElement) {
return document.getElementById(idElement).value;
}
function setValue(idElement,val) {
return document.getElementById(idElement).value = val;
}
var ids = Array("eight_by_seven_right_side","nine_by_seven_right_side","ten_by_eight_right_side");
var widths = Array(
getValue("eight_by_seven_width_right_side"),
getValue("nine_by_seven_width_right_side"),
getValue("ten_by_eight_width_right_side")
);
var values = Array();
for(i=0;i<ids.length;i++) {
if (!prevValue[i]) { prevValue[i]=0; }
values[i] = getValue(ids[i]);
}
var framewidth = getValue("framewidth");
var totaldoorwidth = 0;
var totaldooramount = 0;
var framewidthtotaldoorwidth;
var framespace;
for(i=0;i<ids.length;i++) {
totaldoorwidth += values[i] * widths[i];
totaldooramount += parseInt(values[i], 10);
}
framewidthtotaldoorwidth = framewidth - totaldoorwidth;
framespace = totaldooramount + 1;
if (framewidthtotaldoorwidth < framespace) {
alert("You have to many doors on the right side");
for(i=0;i<ids.length;i++) { setValue(ids[i],prevValue[i]); }
} else {
prevValue = values;
}
}
updated fiddle
Edit: In answer to your follow on question in the comment:
is there a way to make it loop through and find the next size down that would work if they choose to many?
Yes, you can have it iterate the values to find one that fits, as long as the initial values are valid (in this case no doors is a perfect initial value). This also means you don't need to worry about storing any previous value.
I had some fun with this a took some liberties with your code.
First, a few changes in the HTMl:
for each element with an onChange, have it pass the element that was changed so we can tell which one to modify:
<select ... onchange="doorsrightsideFunction(this)">
change the IDs of the _width and _height hidden inputs so they are of the form <id of select element>_width (i.e. the width element for the select with id="eight_by_seven_right_side" should be "eight_by_seven_right_side_width" so you just need to take id + "_width" to find it)
wrap all of the door select elements in a <div id="doorchoices"> ... </div> so they can be found programmatically. This way adding a new door to the system is as simple as adding the select and height/width hidden inputs within the containing div, and the javascript finds and uses them automagically.
The javascript changes, I tried to comment inline:
//make ids and widths global to this page so we only have to construct it on page load
var ids;
var widths;
function getValue(idElement) {
var el = document.getElementById(idElement);
if (el) {
return parseInt(el.value);
} else {
return null;
}
}
function setValue(idElement, val) {
return document.getElementById(idElement).value = val;
}
window.onload = function () {
//construct id list from elements within the containing div when the page loads
ids = Array("framewidth");
widths = Array(null);
var container = document.getElementById("doorchoices");
var selections = container.getElementsByTagName("select");
var i;
for (i = 0; i < selections.length; i++) {
ids.push(selections[i].id);
// get each door's width from the _width element that matches the id
widths.push(getValue(selections[i].id + "_width"));
}
}
// el is the 'this' passed from the select that changed
function doorsrightsideFunction(el) {
console.log(widths);
console.log(ids);
var changedIndex = ids.indexOf(el.id);
//get all of the option elements of the changed select
var possibleValueEls = el.getElementsByTagName("option");
var values = Array();
var possibleValues = Array();
var framewidth;
var curValue;
var totaldoorwidth;
var totaldooramount;
var framewidthtotaldoorwidth;
var framespace;
var i;
function calcWidth() {
totaldoorwidth = 0;
totaldooramount = 0;
var i;
framewidth = values[0];
//start with 1 since index 0 is the frame width
for (i = 1; i < ids.length; i++) {
console.log(i + ")" + ids[i] + " " + values[i] + "(" + widths[i] + ")");
totaldoorwidth += values[i] * widths[i];
totaldooramount += parseInt(values[i], 10);
}
framewidthtotaldoorwidth = framewidth - totaldoorwidth;
framespace = totaldooramount + 1;
}
// get all possible values from the option elements for the select that was changed
for (i = 0; i < possibleValueEls.length; i++) {
possibleValues.push(parseInt(possibleValueEls[i].value));
}
// values should be increasing in order
possibleValues.sort();
// except framewidth should be decreasing
if (el.id == "framewidth") {
possibleValues = possibleValues.reverse()
};
// get the value of each element
for (i = 0; i < ids.length; i++) {
values[i] = getValue(ids[i]);
if (changedIndex == i) {
curValue = values[i]
};
}
calcWidth();
console.log(framewidthtotaldoorwidth);
console.log(framespace);
if (framewidthtotaldoorwidth < framespace) {
alert("You have to many doors on the right side");
// start with the current value and try each until it fits
for (validx = possibleValues.indexOf(curValue); validx >= 0, framewidthtotaldoorwidth < framespace; validx--) {
//change the value in the values array
values[changedIndex] = possibleValues[validx];
//change the select to match
setValue(el.id, possibleValues[validx]);
//see if it fits
calcWidth();
}
}
}
New fiddle
and the simplicity of adding another door size - just add this to the HTML:
<input type="hidden" name="twelve_by_ten_right_side_width" id="twelve_by_ten_right_side_width" value="12" />
<input type="hidden" name="twelve_by_ten_right_side_height" id="twelve_by_ten_right_side_height" value="10" />
<br />
<label for="twelve_by_ten_right_side">12x10:</label>
<select id="twelve_by_ten_right_side" onchange="doorsrightsideFunction(this)">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
New door fiddle

HTML Connected dropdown (more than one)with number as value

Basically, I want to create more then 1, dropdowns, which contains numbers as value eg.
<select id="dp1">
<option value='op1'>1</option>
<option value='op2'>2</option>
<option value='op3'>3</option>
</select>
<select id="dp2">
<option value='op1'>1</option>
<option value='op2'>2</option>
<option value='op3'>3</option>
</select>
<select id="dp3">
<option value='op1'>1</option>
<option value='op2'>2</option>
<option value='op3'>3</option>
</select>
this is just one dropdown. lets say I have 3 dropdown lists with same numbers with different default value eg. dp1 -> 1, dp2 -> 2, dp3 -> 3 . So, Now if user changes value of dp3 to 1 the value of other dropdown list should get change automatically as per sequence like dp1 -> 2 and dp2 -> 3.
if i explain it with other example if user changes value of dp3 to 2 the value dp1 should not change and value of dp2 -> 3should change.
How is it possible to do using Javascript / jquery. (I am using php to populate dropdown from database)
Thank you in advance.
if you just want to change the previous dropdownlists buy changing the current dropdownlist maybe this sample code can help you :
$("select").change(function(){
var selectValue = $(this).val();
var toRemove = 'op';
var value = selectValue.replace(toRemove,'');
var selectId = $(this).attr('id');
var toRemove = 'dp';
var id = selectId.replace(toRemove,'');
id = id-1;
for(var i = id; i>=1; i--){
value = value -1;
var newValue = "op"+value;
$("#dp"+i).val(newValue);
}
});
If the data you're using is really just numeric, then something like this will work. Click here for a jsfiddle example that demonstrates the behavior I think you're looking for.
<select id="dp1" class="dropdown"></select>
<select id="dp2" class="dropdown"></select>
<select id="dp3" class="dropdown"></select>
<script type="text/javascript">
var values = [1, 2, 3];
$(function() {
initDropdowns();
$('select.dropdown').change(function() {
setDropdownValues($(this).attr('id'));
});
});
function initDropdowns() {
var optionsHtml = '';
for(var i = 0; i < values.length; i++) {
var value = values[i];
optionsHtml += '<option value="' + value + '">' + value + '</option>';
}
$('select.dropdown').append(optionsHtml);
setDropdownValues();
}
function setDropdownValues(excludeListId) {
var valuesClone = values.slice();
var $dropdowns = $('select.dropdown');
if(excludeListId) {
valuesClone.splice(Number($('#' + excludeListId).val()) - 1, 1);
}
$('select.dropdown').each(function() {
if($(this).attr('id') !== excludeListId) {
$(this).val(valuesClone[0]);
valuesClone.splice(0, 1);
}
});
}
</script>

Categories

Resources