How to select an option via jquery - javascript

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

Related

Make the select think ctrl is pressed in javascript?

I'm makin a select with the multiple property enabled.
<select id="lst_prueba1" size="8" multiple>
<option>Alderaan</option>
<option>Corellia</option>
<option>Endor</option>
<option>Kashyyyk</option>
<option>Mustafar</option>
<option>Naboo</option>
<option>Nar Shaddaa</option>
<option>Tatooine</option>
<option>Yavin</option>
</select>
But i want to select the options without the need of pressing the ctrl key.
Is there a way to fake the press using javascript or what could in the onchange event?
The answer provided here didn't work for me:
How to avoid the need for ctrl-click in a multi-select box using Javascript?
Although I'd suggest using checkboxes as mentioned in the comments, this should do the trick. Works in Chrome, Firefox and Edge. Might want to test more depending on your requirements.
<script>
var selected = {};
$("#lst_prueba1").click(function(e) {
var options = this.options;
var option;
var value;
value = $(this).val();
for (var i = 0; i < options.length; i++) {
option = options[i];
if (option.value == value) {
selected[value] = !selected[value];
}
option.selected = !!selected[option.value];
}
});
</script>

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

Onchange event for multiple dropdowns issue

I have a list like this:
<form>
<select id="List_22" >
<option value="default">Default</option>
<option value="1">Oil</option>
<option value="2">Gas</option>
<option value="3">Power</option>
</select>
<form>
I want to launch a function upon dropdown change, so this works fine:
document.getElementById("List_22").onchange = function() {...
I however have multiple dropdowns that should all use the same function. I have tried to use the below wildcard but it does not work
document.getElementById("[id^=L]").onchange = function() {
What am I doing wrong? I am going slightly barmy. Thank you all for your time.
The issue is document.getElementById looks for an exact ID match for a single element, so it doesn't support attribute selectors and nor does it return multiple elements.
In plain old JavaScript you can use document.querySelectorAll which supports CSS selectors, and the attribute selector. Note that this isn't supported before IE8.
var list = document.querySelectorAll('[id^=L]');
for(var i=0; i<list.length; i++){
list[i].onchange = function(){
// do something on change....
};
}
Or since you have jQuery tagged, a jQuery version:
$('[id^=L]').change(function(){
// do something on change....
});
Side note: In both cases, I would prefer to make the attribute selector more specific such as select[id^=List_].
$('form select').on('change', function(){
// Your code here
});
In plain javascript, you could do this generic search which should work in every browser and no need to regular expressions.
var dropdowns = document.getElementsByTagName("select"),
item;
for (var i = 0, count = dropdowns.length; i < count; i++) {
item = dropdowns[i];
if (item.id && item.id.indexOf("List_") == 0) {
item.onchange = function () {
alert(this.options[this.selectedIndex].text);
};
}
}
Working example: http://jsfiddle.net/Rq9nb/
Best procedure for cases like this would be, to add a common class to all the dropdowns for which you want to call the function on change. For ex: add 'trigger-change' class for all your required dropdowns. Then below bind event should work perfect for you.
$('form select.trigger-change').on('change', function(){
// Your code here
});
This way, you can choose the dropdowns for which you want to trigger a change event funciton and you can also have dropdowns which are not triggering the change event functions.
Hope this helps :)

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