I have a drop down box with values dynamically populated from a database. So, its HTML is somewhat like this:
<select id="productclass">
<option value="1">Name1</option>
<option value="7">Name2</option>
<option value="11">Name11</option>
</select>
Where the id's and the names are pulled from the database.
I need to be able to write JavaScript to select the option with a specific value. So, how can I make option #7 selected using JavaScript? I can use JQuery too if it's easier.
If you want to select the option with value 7, use:
document.getElementById("productclass").value = "7";
$("#productclass").val("7"); //jQuery
If you mean option number 7 by "#7", use:
document.getElementById("productclass").selectedIndex = 6;
// Indexes are zero-based, the 7th element is referred through index 6
Try this with jquery:
$('#productclass').val('7');
Here's a jsfiddle
Related
Given the following jQuery plugin: http://selectric.js.org/index.html which replaces the functionality of that of a regular select box by using custom UL LI lists,
Based on the plugins documentation, I know that you can programmatically select an option value if you already know the index to select by using the following code:
$('#idofselectbox').prop('selectedIndex', 3).selectric('refresh');
But they do not include a sample to be able to find and select an option value by a value.
For example,
Let's say i'd like to select the option value named 'apples' without actually knowing its index in the select box. Is this even remotely possible?
<select id="idofselectbox">
<option value="oranges">oranges</option>
<option value="pears">pears</option>
<option value="apples">apples</option>
<option value="strawberries">strawberries</option>
</select>
You can set the value as if it's a regular combo box, then call refresh on selectic to refresh the UI.
$('#idofselectbox').val('apples').selectric('refresh');
How do I get all select elements that do not have an option selected using jQuery?
<select id="one">
<option value=""></option>
<option value="test"></option>
</select>
<select id="two">
<option value=""></option>
<option selected value="test"></option>
</select>
What would the jQuery selector be that would return just #one based on no selection?
Refer to https://stackoverflow.com/a/63588880/3499595 if your case is not similar to OP (default value is "")
$('select option:selected[value=""]').parent()
Selects all the :selected options of all the select elements
Checks if the selected option has a value of "", which in your case means no option is actually selected.
Returns the parent (which would be a select)
You can take advantage of jQuery's .parent() and .not() functions. See below:
// selector for all 'select' elements with any option below it
var all = $("select>option").parent(); // alternative $("select")
// selector for all 'select' element with a selected child
var selected = $("select>option[selected]").parent();
// the subtraction set "all - selected" achieved by `not`.
var unselected = all.not(selected);
Note that jQuery's parent takes care of removing duplicates from a set of parents of child elements.
JsFiddle here.
The accepted answer gives all select elements with a selected option whose value is empty(""), which does answer the question in regard to the OP's sample HTML, where options with empty values are given, but it doesn't really answer the title question.
There is a difference between selecting an option with an empty value, and not selecting any option at all.
To select all select elements with no option selected, use
$('select').not(':has(option:selected)')
If you have jquery library then try
$('select option').filter(function(i,d){return !d.hasAttribute("selected")});
This question already has answers here:
Get selected value in dropdown list using JavaScript
(32 answers)
Closed 6 years ago.
Sample of <select> HTML form element from W3Schools (a bit modified):
<select>
<option value="a">Option A</option>
<option value="b">Option B</option>
/*...*/
</select>
As far as I could see, neither option nor select has id property, so the good old document.getElementById("name of select element").value does not work.
But then, how can I put the value attribute of the option that is selected in the list into a JS variable?
I'm aware that it can be done by a function call, e.g. when I push a button element, but what do I have to write into that function?
Aside from just giving it an id, you can add an onchange event:
<select onchange="yourfunction(this.value)">
...
There are also other ways to access elements in your DOM. For example, assuming this is the only (or first) select on your page you could access its value with a line like this:
var val = document.getElementsByTagName("select")[0].value;
If you don't have an id to work with, the DOM provides a few other APIs that you can use, but probably the most versatile is:
document.querySelector("CSS Selector Here");
So, you could use a selector that finds the select element by the tag name select or by its position in the DOM or by a class name applied to it, etc.
Then, to get the value, you'd write this:
var val = document.querySelector("CSS Selector Here").selectedIndex.value;
I need to add a "fake" <option> to a <select>, that will be shown as the selected one, but that can't be selected in the dropdownmenu if the user want to change item.
For example: I have a page that displays 10 fruits. Each fruit has his weight. Using the select, I can filter the fruits by weight:
<select id="fruits">
<option>1 kg</option>
<option>2 kg</option>
<option>3 kg</option>
</select>
if I select the 2nd option (2kg), the page will remove every fruit that has weight != 2kg, and obviously show only those with weight == 2kg.
Now I need to add a "weight range", for example "show fruits whose weight is between 1 and 2 kg". I don't want to add a new option to the , I just want to filter the table showing fruits with weight between the selected range (1 and 2kg), and show this range as the selected value in the select. So my CLOSED dropdown menu will have value = "1-2kg", but if I click on the select, I will not find "1-2kg" option (that's why I wrote "fake" option in the title).
In a nutshell I just want to edit the selected-shown select text, not his options... Something like, using JS
var select = document.getElementById("fruit-select");
select.value = "1-2kg";
obviously this is not working because the option "1-2kg" does not exists..
Is this possible? I hope I was clear enough.. Thanks in advance for any helps, best regards
Solution (not working on Safari...)
Thanks to Ricardo I came to this solution: http://jsfiddle.net/4suwY/5/
HTML:
<select id="asd">
<option>hello</option>
<option>I'M THE CHOSEN ONE</option>
<option>asd</option>
<option>wer</option>
<option>qwe</option>
</select>
JS:
var sel = document.getElementById("asd");
var optnz = sel.getElementsByTagName("option")[1];
sel.value = optnz.value;
optnz.style.display = "none";
the "I'M THE CHOSEN ONE" option is displayed as selected, but is not clickable (not even visible in the options list)
Thanks guys!
I think what you need to do here, is actually have a visible select with all those values, 1kg, 2kg, etc and then you have a hidden select, that will contains those ranges, like 1-2kg, etc (if the ranges are fixed). Everytime you select something from the visible dropdown you change the selected item of the hidden dropdown to the desired range.
It sounds like you want to include a range of weights. You may want to consider a different type of input, such as a range slider. Here's an example from the jQuery UI project. I'm not suggesting you use jQuery UI per se, just showing you one way it can be implemented.
You could use <select multiple> and whenever someone selects more than one option you get the maximum and minimum and show that interval.
try this:
http://jsfiddle.net/4suwY/4/
the only problem I see is losing the value on select click on this function:
$("#asd").mousedown(function () {
$("#asd option[value='1-2kg']").remove().change();
});
I have a select dropdown that could possibly contain over 1000 items for a large customer.
<select name="location" id="location">
<option value="1">Store# 1257</option>
<option value="2">Store# 1258</option>
...
<option value="973">Store# 8200</option>
<option value="974">Store# 8250</option>
<option value="975">Store# 8254</option>
<option value="976">Store# 8290 Fuel Center</option>
</select>
I also have a text box and when the user types in text I want to move the selected item in the dropdown.
For example, if the user types 82 then I want to move to the first item in the box where an 82 exists which would be value 973. If the user types 825 then move to 974, etc. If the user types Fuel, find the first option containing that string.
I am currently using jquery as my javascript library.
What do you suggest for solving this? Should I switch to an autocomplete? If so I need something that has a arrow to dropdown the entire list as some customers may only have 3 or 4 to select from.
Thanks.
Given a variable searchFor that contains the search string, you can select the first option that contains that text with this jquery snippet:
$("#location option[text*=" + searchFor + "]:first").attr("selected", true);
So if you have a text input with the id selectSearchBox, you could write it like this:
$("#selectSearchBox").keyup(function () {
var searchFor = $(this).val();
$("#location option[text*=" + searchFor + "]:first").attr("selected", true);
});
Using jQuery autocomplete plugin might be the best option for you. You can have a look at a previous answer here on SO (please, don't do that select => array translation, use an array or a server side script).