I have a requirement When selected a dropdown value, it has to filter or remove the values of other dropdown which has index that should be always greater than selected index of first dropdown.
Ex: First Dropdown values:
01:00
01:30
02:00 // suppose i select 02:00 here
02:30
03:00
03:30
04:00
04:30
05:00
05:30
Second Dropdonw Values (on selected 02:00 in the above dropdown should look like below)
02:30
03:00
03:30
04:00
04:30
05:00
05:30
(Im using C# with Asp.net here.)
Any javascript to achieve above would be greatly appreciated
and using script as below as Salman Suggested
<body onload="select()">
<script language="javascript">
function select(){
var select1 = document.getElementById("ddlFrom");
var select2 = document.getElementById("ddlTo");
select1.onchange = function filterDDL() { // empty select2
while (select2.firstChild) {
select2.removeChild(select2.firstChild);
}
if (select1.selectedIndex == 0)
{
return;
}
for (var i = select1.selectedIndex; i < select1.options.length; i++)
{
var o = document.createElement("option");
o.value = select1.options[i].value;
o.text = select1.options[i].text;
select2.appendChild(o);
}
}
}</script>
but not working...please help on this
Thanks in advance
Edit (using jQuery to get desired results):
<select id="one">
<option value="01:00">01:00</option>
<option value="01:30">01:30</option>
<option value="02:00">02:00</option>
<option value="02:30">02:30</option>
<option value="03:00">03:00</option>
<option value="03:30">03:30</option>
</select>
<select id="two"></select>
<script type="text/javascript">
$(function () {
$("#one").change(function (e) {
$("#two").empty();
var options =
$("#one option").filter(function(e){
return $(this).attr("value") > $("#one option:selected").val();
}).clone();
$("#two").append(options);
});
});
</script>
Vanilla JavaScript solution and demo.
HTML
<select name="select1" id="select1">
<option value="">-- select an option --</option>
<option value="01:00">01:00</option>
<option value="01:30">01:30</option>
<option value="02:00">02:00</option>
<option value="02:30">02:30</option>
<option value="03:00">03:00</option>
<option value="03:30">03:30</option>
<option value="04:00">04:00</option>
<option value="04:30">04:30</option>
<option value="05:00">05:00</option>
<option value="05:30">05:30</option>
</select>
<select name="select2" id="select2">
</select>
JavaScript
// this function must be wrapped inside onload event
var select1 = document.getElementById("select1");
var select2 = document.getElementById("select2");
select1.onchange = function() {
// empty select2
while (select2.firstChild) {
select2.removeChild(select2.firstChild);
}
if (select1.selectedIndex == 0) {
return;
}
for (var i = select1.selectedIndex; i < select1.options.length; i++) {
var o = document.createElement("option");
o.value = select1.options[i].value;
o.text = select1.options[i].text;
select2.appendChild(o);
}
}
There are multiple ways to achieve this, each might be good for a different useage.
Filter by value
#Craig has suggested it already. Give the dropdown options values. When something's selected in the first one, values lower or equal to its value are removed from the second dropdown: http://jsfiddle.net/q8mLH/
Using an array of available pairs
Create an array of the pairs you're interested in, then when select 1 is changed, update select2 available options based on what is defined in your array of allowed pairs: http://jsfiddle.net/AU6hq/
AJAX + database pairs
I'm not going to specify an example here, sorry, but the general idea is this: you need to have some tables in your database, let's say "countries" and "cities", where each country has an ID, and each city has its own unique ID plus the ID of the country where it lies. You'll want to display only the cities in the selected country, probably.
You bind the change() event to the counties select and load the contents of the second select via an ajax call, querying the database for the cities that lie in the selected country.
There might be more, but I don't quite feel like thinking too much today ;). Anyway, I hope this helps.
[EDIT]
My examples use jQuery, I hope it's not a problem.
Related
Based on this useful topic Use jQuery to change a second select list based on the first select list option I try to adapt the code for my purposes.
My problem is that for some reasons I cannot have the exact same integer values in my 2 selection. I only can provide something close as:
<select name="select1" id="dropDown">
<option value="fruit">Fruit</option>
<option value="animal">Animal</option>
<option value="bird">Bird</option>
<option value="car">Car</option>
</select>
<select name="select2" id="dropDown_2">
<option value="fruit-01">Banana</option>
<option value="fruit-02">Apple</option>
<option value="fruit-03">Orange</option>
<option value="animal-01">Wolf</option>
<option value="animal-02">Fox</option>
<option value="animal-03">Bear</option>
<option value="bird-01">Eagle</option>
<option value="bird-02">Hawk</option>
<option value="car-01">BMW<option>
</select>
The js to be modified is:
$("#dropDown").change( function() {
if ( $(this).data('options') == undefined ) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data( 'options', $("#dropDown_2").find('option').clone() );
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$("#dropDown_2").html(options);
} );
I know that there are some js techniques to subtract substrings and similar stuff. But my skills are not so good to exactly say how. Is there anyone willing to help me? I need to filter the second options with its values based (but not identical) on the values of the first. Hope I explained myself sufficiently. Many many thanks!
EDIT
First of all sorry for not explaining myself sufficiently. I have to add that I cannot change the markUp!
So I inserted an each loop before the code that Shiran kindly delivered me to prepare it like so:
$("#dropDown_2").find('option').each( function() {
var $this = $(this);
var val = $this.val();
var myFilter = val.slice(0,-3)
$this.addClass( myFilter );
// $this.data('filter', myFilter ); does not work don’t know why
} );
Which seems to work at least in principle. Yet, for reasons that remain obscure for me sadly my attempt to attach data-filter to my option elements wasn’t accepted. So I had to go for classes which worked (at least for the loop).
I then tried to modify the code ending up with the following:
$("#dropDown").change(function() {
var filters = [];
if ($(this).attr('class') == "") {
$(this).find("option").each(function(index, option) {
if ($(option).attr('class') != "")
filters.push($(option).attr('class'));
} );
} else {
filters.push($(this).attr('class'));
}
$("#dropDown_2").html("");
$.each(filters, function(index, value) {
$options.find("option." + value ).clone().appendTo($("#dropDown_2"));
} );
} );
But as you can guess this didn’t work. :-(
And I also noted that the values of my filter array are the class (would be analogue to the filter value in the original) of my select not of the options of it. But obviously Shorans code did work well. What did I wrong here?
Please help, I am getting grey hair with this!! Thanks so much in advance!
$(this).data("options") gets:
<select data-options="the data here"> ==> "the data here"
Here's a working version:
(notice how I used data-filter in the second select and in the last each loop in the javascript part)
$(document).ready(function() {
var $options = $("#dropDown_2").clone(); // this will save all initial options in the second dropdown
$("#dropDown").change(function() {
var filters = [];
if ($(this).val() == "") {
$(this).find("option").each(function(index, option) {
if ($(option).val() != "")
filters.push($(option).val());
});
} else {
filters.push($(this).val())
}
$("#dropDown_2").html("");
$.each(filters, function(index, value) {
$options.find("option").each(function(optionIndex, option) { // a second loop that check if the option value starts with the filter value
if ($(option).val().startsWith(value))
$(option).clone().appendTo($("#dropDown_2"));
});
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="select1" id="dropDown">
<option value="">All</option>
<option value="fruit">Fruit</option>
<option value="animal">Animal</option>
<option value="bird">Bird</option>
<option value="car">Car</option>
</select>
<select name="select2" id="dropDown_2">
<option value="fruit-01">Banana</option>
<option value="fruit-02">Apple</option>
<option value="fruit-03">Orange</option>
<option value="animal-01">Wolf</option>
<option value="animal-02">Fox</option>
<option value="animal-03">Bear</option>
<option value="bird-01">Eagle</option>
<option value="bird-02">Hawk</option>
<option value="car-01">BMW
<option>
</select>
Currently I am working on a site where I do not have access to the perl generated options of a drop down list. The drop downs are populated dynamically and not all options are available to all users.
The code I am able to work with is shown here.
<select class="fielddrop" name="PRIMARY_POS" size="1" style="width: 187px;" ></select>
PRIMARY_POS
populates each option that is able to be selected.
The actual output as seen when the page renders is
<select class="fielddrop" name="PRIMARY_POS" size="1" style="width: 187px;">
<option value="0">None Selected
<option value="155935">Option4
<option value="155934">Option3
<option value="155905">Option2
<option value="155933">Option1
<option value="155932">Option5
</select>
What I need to be able to do is set a sort order based on a hidden attribute that is assigned based on the text value
So in the above example. I need the drop downs ( Important as their are mulitple drop downs on the page ) to be able to be sorted by a not yet created attribute
So that the above code might then be
<option value="0">None Selected
<option sortvalue="5" value="155935">Option4
<option sortvalue="4" value="155934">Option3
<option sortvalue="3" value="155905">Option2
<option sortvalue="2" value="155933">Option1
<option sortvalue="1" value="155932">Option5
</select>
The sortvalue being set base don the Text value of the option select. So that a sortvalue of 5 would be assign to Option4. Just a smaple as the text will need to be assigned.
End result should be that the Drop down list now has a custom attribute of Sortvalue and the select drop down is now sorted by that value.
Once again, I can not directly change the attributes but can manipulate the results. Hope that was easy to follow, which I doubt :/
You can create an object where the keys are the text and values are sort order. Then loop over options and add attribute based on that map
var optsMap = {
"Option4": 5,
"Option5": 1
......
};
var $select = $('select[name=PRIMARY_POS]')
$select.find('option').attr('data-sortvalue', function(){
return optsMap[$(this).text()] ||0;
}).sort(function(a,b){
return +($(a).data('sortvalue')||0) - +($(b).data('sortvalue')||0);
}).appendTo($select);
You can then read the value using:
$select.change(function(){
alert($(this).find(':selected').data('sortvalue'));
})
If all you are needing is sorting and don't need attribute can remove one step
DEMO
Common practice is to prefix those "added attributes" with data. You could try something like this with jQuery, if I'm understanding you correctly.
Example fiddle: https://jsfiddle.net/30cvudz8/7/
<select class="my-select">
<option data-sort-value="3" value="1">Option 1</option>
<option data-sort-value="5" value="2">Option 2</option>
<option data-sort-value="4" value="3">Option 3</option>
<option data-sort-value="1" value="4">Option 4</option>
<option data-sort-value="2" value="5">Option 5</option>
</select>
var optionList = new Array();
$('select.my-select option').each(function() {
optionList[optionList.length] = $(this).attr('data-sort-value')+'::'+$(this).val();
});
optionList.sort(); // sort it
var newOptionList = '';
for(var i = 0; i < optionList.length; i++) {
// recreate option
var parts = optionList[i].split('::');
newOptionList += '<option value="'+parts[1]+'" data-sort-value="'+parts[0]+'">Option '+parts[1]+'</option>';
}
// wipe and repopulate the select list
$('select.my-select').html(newOptionList);
To add an attribute (like data-sort-value) after you have a select list, you can do something like this:
$('select.original option').each(function() {
var sortingValue = getSortingValueFromText($(this).text());
$(this).attr('data-sort-value', sortingValue);
});
I have a problem when I get the values of Selected options.
Let me explain I have a list of options :
<select>
<option value='1'>Option1</option>
<option value='2'>Option2</option>
<option value='3'>Option3</option>
<option value='4'>Option4</option>
<option value='5'>Option5</option>
</select>
I get the values and I inserts them into a variable for each Selected option and I put them in an array like this :
$("select option:selected").each(function()
{
var listValO = new Array();
var idOption = $("select option:selected").val();
listValO.push(idOption);
});
If I choose only one selected option, it works but when I select several options at the same time, the each () function inserts in the array the same value for the number of selected options.
when I click on the submit button, the array contains listValO several times the same value.
<select>
<option selected value='1'>Option1</option>
<option selected value='2'>Option2</option>
<option selected value='3'>Option3</option>
<option>Option4</option>
<option>Option5</option>
</select>
listValO returns just 3 times [1,1,1]. In fact, it seleted the first which I clicked or I want in my array [1,2,3].
Sorry for English mistakes if any. I hope you understand my problem and thank you for your future response.
As well as the other answers (using multiple attribute, and using $(this)), you are re-declaring the array for each occurrence of a selected option. Try declaring it outside:
var listValO = new Array();
$("select option:selected").each(function()
{
var idOption = $(this).val();
listValO.push(idOption);
});
Firstly, you need to add the multiple attribute to the select so you can select multiple options. Second, you're redeclaring a new array inside the each callback, so at the end you'll only ever have one option.
You should use .val() instead:
Markup:
<select multiple>
<option selected value='1'>Option1</option>
<option selected value='2'>Option2</option>
<option selected value='3'>Option3</option>
<option>Option4</option>
<option>Option5</option>
</select>
Javascript:
var optionsArray = $("select").val();
You need to add attribute multiple in select to select multiple value:
<select multiple="multiple">
<option selected value='1'>Option1</option>
<option selected value='2'>Option2</option>
<option selected value='3'>Option3</option>
<option>Option4</option>
<option>Option5</option>
</select>
Js code: You are iterating over the selected options, you should rather iterate over to select itself to ensure that selected options are added to array once only.
var listValO = new Array();
$("select").each(function()
{
listValO.push($(this).val());
});
//console.log(listValO) for test purpose
Working Demo
I'm using .val() in jQuery to retain the value of an options menu onChange.
How would I retain the number (as in as it is ordered) of the item in the drop down using jQuery?
<select>
<option> //option 1
<option> //option 2
</select>
Here is what I have set up now:
<select id="start_month" onChange="getMonthDay()">
<option>Jan</option>
<option>Feb</option>
<option>March</option>
<option>April</option>
<select>
Using,
function getMonthDay()
{
$('#start_month').val()
}
I can get whatever value is selected, but my question is how do I get the Number down of this value in the markup? For March, I would want 3.. and so on
Can you reformulate your question better? I'm still lost in what do you want.
But, nevertheless here is how <select> works in jQuery
<select id="selection">
<option value="val_1">value 1</option>
<option value="val_2">value 2</option>
</select>
$("#selection").val() will give you val_1 or val_2 depending on witch item is currently selected.
If you want to go through all options and check the selected on, you can use
$("#selection option:selected").val();
or itenerate through all <option>'s
$("#selection option").each(function() {
if( $(this).is(":selected") ) {
var v = $(this).val();
}
});
If you want to retain all options you can easily clone them or assign them as data, if you want to keep those values throughout the pages, use Local Database or Cookies to persist the data.
To answer your question after your update:
First: Why don't you have:
<select id="start_month" onChange="getMonthDay()">
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">March</option>
<option value="4">April</option>
<select>
And use the value of the selected item?
Second: Just use what I wrote above and itenerate through the options
$("#start_month option").each(function(index, element) {
if( $(this).is(":selected") ) {
// get index position, remember to add 1 as arrays start at 0
var n = index;
// break each
return false;
}
});
You'd get a list of the <option> elements, find the selected one, and use index:
var $opts = $('#start_month option');
var zero_based_index = $opts.index($opts.filter(':selected'));
Demo: http://jsfiddle.net/ambiguous/HyukW/
Just add 1 if you want a one-based index.
I made something like this,with zero based key ;
<select id='deneme'>
<option>Val1</option>
<option>Val2</option>
<option>Val3</option>
<option>Val4</option>
</select>
$('#deneme').change(function(){
$.each( $('#deneme').children('option'),function(key,value){
if($(this).is(':selected'))
alert(key)
})
})
u can check from here http://jsfiddle.net/8JZCw/
No need for any iteration here, let jQuery do that for you, just get the selected index and increment...
$('#start_month option:selected').index() + 1
I needed some help updating the price on a page based on a dropdown selection.
This is what code with some help we came up with:
var price = new Array('','$2.00','$45.00','$60.00');
$(function(){
$('select[name=material]').change(function(){
document.getElementById('pprice').innerHTML = price[$(this).val()];
});
// Trigger on dom ready
$('select[name=material]').change();
});
Which works if my dropdown is structured like this:
<select name="material">
<option value="">-- Please Select --</option>
<option value="1">Wood</option>
<option value="2">Plastic</option>
<option value="3">Metal</option>
</select>
But if for any reason the the dropdown was to be like this:
<select name="material">
<option value="">-- Please Select --</option>
<option value="3">Metal</option>
<option value="4">Cloth</option>
<option value="5">UPVC</option>
</select>
it would not work (because the value option is not 1,2,3). The value is the id for the material. Hope this makes sense and that someone can help me to get this working.
Thanks
Dino
You're changing the price based on the value, and using that as the item from your price array... but your price array only has 4 values. In your second select, you're asking it to return price[4] or price[5], which would cause an error.
Change this:
var price = new Array('','$2.00','$45.00','$60.00');
To this:
var price = new Array('','$2.00','$45.00','$60.00','$cloth price','$upvc price');
Fiddle here.
EDIT: Updated method (with minimal change to your existing layout/logic)
$(function() {
$('select[name=material]').change(function() {
var price = $(this).val().split("_");
$("#id").html(price[0]);
$("#price").html("$" + price[1]);
});
});
HTML (adding the price to each option value, split by "_" in JS)
<select name="material">
<option value="0_0">-- Please Select --</option>
<option value="1_2">Wood</option>
<option value="2_2">Plastic</option>
<option value="3_45">Metal</option>
</select>
<select name="material">
<option value="0_0">-- Please Select --</option>
<option value="3_60">Metal</option>
<option value="4_50">Cloth</option>
<option value="5_80">UPVC</option>
</select>
<div>ID: <span id="id">TBD</span><br />Price: <span id="price">TBD</span></div>
Just select price using the selectedIndex of your <select>:
var price = new Array('','$2.00','$45.00','$60.00');
$(function(){
$('select[name=material]').change(function(){
document.getElementById('pprice').innerHTML = price[this.selectedIndex];
});
// Trigger on dom ready
$('select[name=material]').change();
});
Or, use an object instead of an array for price:
var price = {
"4": "$2.00",
"5": "$45.00",
"6": "$60.00"
};
$(function(){
$('select[name=material]').change(function(){
document.getElementById('pprice').innerHTML = price[$(this).val()];
});
// Trigger on dom ready
$('select[name=material]').change();
});
Update: Here is a jsfiddle with updated code to get your single price array to work:
Your price arrayhas a length of 4 and starts at index 0.
Your first option must have a value of '0' or it will return undefined from the price array:
<select name="material">
<option value="0">-- Please Select --</option>
<option value="1">Wood</option>
<option value="2">Plastic</option>
<option value="3">Metal</option>
</select>
When you set your option values from 3 to 5, you are trying to access non-existent indexes outside the bounds of your price array.