Changing one select option changes many others (JavaScript, JQuery) - javascript

I have a lot of select drop downs on a jsp page with a long list of elements. All of these drop downs have the same list of elements. Say I have to get the choice in descending order of preference from the user. I made (many) selects in the following way:
<select id="sel1" class="myClass">
<script>
populate(document.getElementById('sel1'));
</script>
</select>
...
<script>
function populate(op1)
{
var myArray = ["Chinese", "Italian", "Indian", ...//a long list of elements
var sel = op1;
for(var i = 0; i < myArray.length; i++) {
var opt = document.createElement('option');
opt.innerHTML = myArray[i];
opt.value = myArray[i];
sel.appendChild(opt);
}
}
</script>
I have to create javascript/JQuery code in such a way that if a user selects an option the first select, that option gets disabled/removed in the others, leaving room for changes later. Say, the user's preference order is: Chinese, Indian, Italian... then on selecting Chinese in the first drop down, it gets disabled/removed from the other drop downs. Then, on selecting Indian from the second, it gets disabled/removed from all the others (including the previous one).
Now, if the user decides his order of preference is actually Chinese, Italian, Indian, .. he should be able to change his choice in such a way that the code doesn't break down. Say, we can have a button for reset and it resets all the choices by calling this function:
function resetFunc()
{
var options = document.getElementsByClassName("myClass");
for (var i = 0, l = options.length; i < l; i++)
{
options[i].selectedIndex = "0";
}
}
Any idea how to accomplish this? I need the code to be browser independent (while googling, I read somewhere that IE doesn't support removal of elements from drop down).
EDIT: Here's what I basically want:
http://jsfiddle.net/RaBuQ/1/
However, there's a problem in this. If a user keeps changing his choices, this thing breaks down. I'm able to select multiple choices.

$('select').change(function(){
var v = $(this).val();
$('select option[value="'+$(this).data('old-val')+'"]').prop('disabled', false);
$(this).data('old-val',v);
if(v != "0"){
$('select option[value="'+v+'"]').not(this).prop('disabled',true);
}
});
Here's a fiddle.
If I selected 'Football', 'Golf', 'Tennis', I'd need to select 'No preference' in the third box before I could then select it in one of the other boxes. I think this is acceptable from a UX perspective.

Since you've tagged this jQuery my example below will utilize that:
function populate() {
var myArray = ["Chinese", "Italian", "Indian"];
$('.myClass').each(function() {
var dis = $(this);
dis.append($("<option>").attr("value", "").text("select"));
$.each(myArray, function(i, o) {
dis.append($("<option>").attr("value", o).text(o));
});
});
}
function init() {
$('.myClass').html('').prop('disabled', false);
populate();
}
$(document).on('change', '.myClass', function() {
$('.myClass option[value="' + $(this).val() + '"]:not(:checked)').remove();
$(this).prop('disabled', true);
});
$('#reset').click(init);
init();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="sel1" class="myClass"></select>
<select id="sel2" class="myClass"></select>
<select id="sel3" class="myClass"></select>
<input type="button" id="reset" value="Reset options" />

The following might not be the most efficient solution, but you should try it if there is nothing better: when you change a select, empty all other selects and then fill them with all the other options.
lets say you have 3 selects: sel1, sel2, sel3
in the onchange event, you could call a function "fill_other_sel(number)" where number is the number of the current selector.
This function should delete current options and then populate checking with the previous selectors so that you dont populate with a previously selected value.
function fill_other_sel(number){
var num_selectors = 3;
while (number <= num_selectors){
number++;
$('#sel'+number).options.length=1;
populate('sel'+number, already_selected_values_array);
}
}
also you might add a parameter to your populate function showing which values have already been selected to prevent them from appearing again

Related

Disable option values in one select dropdown depending on value selected in another

I have a form with two select dropdowns. The first is opening times and the second is closing times. So When the user selects a opening time the closing time cannot be earlier than this.
My Jquery instead disables all the second drop down values instead of only the times earlier as can be seen here: JSFiddle.
$('#open').change(function(){
if($('#close').val()<$('#open').val()){
$('#close').prop('disabled', true);
};
})
How can I get the behaviour I want?
Try this (here is the updated jsfiddle):
$('#open').change(function(){
var that = $(this);
$('#close option').each(function() {
if($(this).val() < that.val()) {
$(this).prop('disabled',true);
} else {
$(this).prop('disabled',false);
}
});
});
It works on Chrome 36, but not on Firefox (haven't tested any browsers besides those two).
Since this behavior is unreliable, you might try dynamically adding options to the second select element based on whatever is chosen in the first select element.
EDIT
See this jsfiddle based on your original fiddle. It will let you dynamically populate the second select element.
var vals = ['00.00', '00.15', '00.30', '00.45', '01.00', '01.15', '01.15'];
for(var i = 0; i<vals.length; i++) {
$('#open').append('<option val="'+vals[i]+'">'+vals[i]+'</option>');
}
$('#open').change(function(){
$('#close').html('');
for(var i = 0; i<vals.length; i++) {
if(vals[i] >= $(this).val()) {
$('#close').append('<option>'+vals[i]+'</option>');
}
}
}).change();
Most browsers do not allow the disabling of individual <option>s in a <select>.
I would fill the second <select> whenever the first is changed.

How to select an option via jquery

I have a select form that looks kind of like this:
<select multiple="multiple" id="id_color_id" name="color_id"">
<option value="1">Red</option>
<option value="2">Blue</option>
<option value="3">Brown</option>
</select>
What I want to do is select the item above via javascript. This is actually part of a hidden form, so all I'm trying to do is leverage the serialize part of the form. I'm thinking it will just be easier to hack that after the serialize then to add this as well, but I also want to deselect any options that have already been selected.
So two questions:
How to select an option via javascript. All I will know is "Red", "Blue" or "Brown". I also have a look up dictionary that can get me the values as well.
How to deselect all options previous to selecting one of the above.
This is related to: Selecting options in a select via JQuery
Native Javascript:
var textToFind = 'Red';
var dd = document.getElementById('id_color_id');
for (var i = 0; i < dd.options.length; i++) {
if (dd.options[i].text === textToFind) {
dd.selectedIndex = i;
break;
}
}
or with jQuery:
$('#id_color_id option:contains('Blue')').prop('selected',true);
with variable:
var blue = "Blue";
$('#id_color_id option:contains(' + blue + ')').prop('selected',true);
And to deselect all selected options:
Native Javascript:
var elements = document.getElementById("id_color_id").options;
for(var i = 0; i < elements.length; i++){
if(elements[i].selected)
elements[i].selected = false;
}
jQuery:
$("#id_color_id option:selected").removeAttr("selected");
To select an option by it's content (considering what you posted is what you have)
$("#id_color_id option:contains('Red')").prop('selected',true);
jsFiddle Demo
You can set the value on the select box using the .val() method. Running this will reset any previously selected values, so you don't need to do anything specific to accomplish that part. You can also use an array to select multiple values, which may be of interest, since you are using a multi select.
$("#id_color_id").val(['1','2']);

How do I add items to multiple drop down lists at the same time with Javascript in Razor?

I'm creating an MVC form, and I have multiple checkboxes and two drop down lists. I have figured out how to populate the first DDL based on what boxes are checked (i.e. empty at the beginning, checking boxes fills the items). However, I want to add another DDL that has the same items and populates in the same manner. My code looks like this:
<script type="text/javascript">
function checkedToggle(value, checked) {
x = document.getElementById("filter1");
y = document.getElementById("filter2");
if (checked == true) {
var option = document.createElement("option");
option.text = value;
x.add(option, null);
y.add(option, null);
}
else {
for (i = 0; i < x.length; i++) {
if (x.options[i].value == value) {
x.remove(i);
y.remove(i);
}
}
}
}
</script>
The else statement obviously removes an item from the list once you uncheck the box.
Now, when you click a check box, rather than adding the item to both lists, it only adds to the second one, and I'm not exactly sure why. Any advice?
You need to create two elements, since in your code you just move the first DOM element to the second select.
var option = document.createElement("option");
var option2 = document.createElement("option");
option.text = value;
option2.text = value;
x.add(option, null);
y.add(option2, null);

how to get the index of value in drop down in javascript?

I have dropdown list on my aspx page. I want to mannually set the selected value which in exist in the dropdown list. this value i am getting in var. i want to set this value as selected value when page get initialize. I want this in javascript. is there any property for dropdown as ddp.SelectedValue='40'..? here I don't know the index of 40 in the list.
selectedIndex is a property of HTMLSelectElement so you can do the following:
<select id="foo"><option>Zero<option>One<option>Two</select>
<script>
document.getElementById('foo').selectedIndex = 1; // Selects option "One"
</script>
And given an OPTION element, you can get its index using the index property:
<select><option>Zero<option id="bar">One<option>Two</select>
<script>
alert(document.getElementById('bar').index); // alerts "1"
</script>
I want to manually set the selected value
Iterate the select's options list to get the option you were interested in and set selected on it:
var options= document.getElementById('ddp').options;
for (var i= 0; n= options.length; i<n; i++) {
if (options[i].value==='40') {
options[i].selected= true;
break;
}
}
this will select the first option with a matching value. If you have more than one option with the same value, or a multiple-select, you may need different logic.
This:
document.getElementById('ddp').value= '40';
is specified by HTML5 to do the same, and has worked in most modern browsers for ages, but still fails in IE, unfortunately (even IE9).
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery 1.6.2.min.js" />
<script language="JavaScript">
$(function() {
quickSelect();
// Handler for .ready() called.
});
function quickSelect() {
var bnd = "40";
if (bnd != "") {
$("#ddp option[value='" + bnd + "']").attr("selected", "selected");
}
}
</script>

How do I access the "displayed" text of a select box option from the DOM?

Given the following HTML:
<select name="my_dropdown" id="my_dropdown">
<option value="1">displayed text 1</option>
</select>
How do I grab the string "displayed text 1" using Javascript/the DOM?
var sel = document.getElementById("my_dropdown");
//get the selected option
var selectedText = sel.options[sel.selectedIndex].text;
//or get the first option
var optionText = sel.options[0].text;
//or get the option with value="1"
for(var i=0; i<sel.options.length; i++){
if(sel.options[i].value == "1"){
var valueIsOneText = sel.options[i].text;
}
}
var mySelect = document.forms["my_form"].my_dropdown;
// or if you select has a id
var mySelect = document.getElementById("my_dropdown");
var text = mySelect.options[mySelect.selectedIndex].text;
Assuming you want the selected option's text:
var select = document.getElementById('my_dropdown');
for(var i = 0; i < select.options.length; i++) {
if(select.options[i].selected) {
break;
}
}
var selectText = select.options[i].text;
In Prototype:
var selectText = $$('#my_dropdown option[selected]')[0].text;
Edit: And jQuery for completeness' sake (assuming jQuery's CSS selector support is roughly equivalent to that of Prototype's):
var selectText = $('#my_dropdown option[selected]').get(0).text;
The displayed text is a child node of the option node. You can use:
myOptionNode.childNodes[0];
to access it, assuming the text node is the only thing inside the option (and not other tags).
EDIT: Oh yeah, as others mentioned, I completely forgot about:
myOptionNode.text;
Assuming you modified your code a bit to have an id / class on the and were using jQuery you could have something like the following. It will pop up an alert for each option with the text of the option. You probably won't want to alert for all the text, but it illustrates how to get at the text in the first place:
$('select#id option').each(function() {
alert($(this).text());
});
If you use a class instead of an id, then you'd just have to change the 'select#id' to 'select.class'. If you didn't want to add a class/id there are other ways to get at the select.
I leave figuring those ways out if you want to go that route as an activity for the reader.
If you were using Prototype, you could get at it like this:
$$('#my_dropdown option[value=1]').each( function(elem){
alert(elem.text);
});
The above is using a CSS selector that says find all option tags with value="1" that are inside the element that has id="my_dropdown".

Categories

Resources