how to get the index of value in drop down in javascript? - 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>

Related

How to prevent select of new option added to select element?

I'm adding new options to select tag and I don't want any of them to be selected. I've tried a couple of ways to do it but every time first option is selected. Here's code:
const $selectField = $('.clsname');
const array = ['option1', 'option2', 'option3'];
$selectField.empty();
array.forEach(function(iter, elem) {
$selectField.append(new Option(iter, elem, false, false));
});
$selectField.show();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select hidden class="clsname"></select>
As far as I understand using new Option() with defaultSelected and selected set to false should resolve the problem.
Additionally, I've tried adding something like this after forEach, but it doesn't work either.
$selectField.children("option:selected").prop("selected", false);
You can set the value of the select field to null after you added your options.
$('#mySelect').val(null)
for(var i = 1; i < 5; i++) {
$option = $('<option></option>').text('Option ' + i).val(i);
$('select').append($option);
}
$('select').val(null)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
</select>

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

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

How to select the DropDownList/Select that triggered the change event

I'm new to JQuery and I noticed this line $('#DivID [type=checkbox]') and I was wondering if I can also find the select or option tags using the same method.
Update: I have a div that has more than more tag, I'm trying to get the DropDownList/Select that it's value's just changed.
Update2 I'm using InstaFilta a JQuery plugin that filter the content based on a customized attribute appended to my content tags. Below is a snippet for the function that do the same when working with CheckBoxes, and I'm trying to edit it to work with DropDownLists/Select controls.
var $ex10Checkboxes = $('#ex10 [type=checkbox]');
$ex10Checkboxes.on('change', function() {
var checkedCategories = [];
$ex10Checkboxes.each(function() {
if ($(this).prop('checked')) {
checkedCategories.push($(this).val());
}
});
ex10.filterCategory(checkedCategories, true);
});
You would find the option tags as follows:
$("#DivID option")
Likewise the select tags:
$("#DivID select")
You can then iterate over the returned objects to inspect the individual elements:
var foo = $("#DivID option");
var i;
for (i = 0; i < foo.length; i += 1) {
console.log(foo[i].val()); //or whatever
}
To find the selected element you could check out this question:
$("#DivID option:selected")
I would suggest checking out the JQuery page on Selectors JQuery Selectors

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']);

Categories

Resources