jQuery - select option in select box [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
jQuery / Programmatically Select an Option in Select Box
I was wondering, is it possible to select an option from a selectbox/combobox directly from jQuery. For example I want to select the option with the value 5 in a select with values from 1 to 10.
The only solution I can think of is to remove all options and recreate them with the right selected value, but that's a bit unefficient.

Just treat the select box as you would any other input element:
$("#MySelectBox").val("5");

You can do this by adding the selected attribute in <option> tag.
$(document).ready(function () {
$('#btn2').click(function(){
$('#sel1 option[value=2]').attr('selected','selected');
});
$('#btn3').click(function(){
$('#sel1 option[value=3]').attr('selected','selected');
});
$('#btn5').click(function(){
$('#sel1 option[value=5]').attr('selected','selected');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<select id="sel1">
<option value='1'>Option 1</option>
<option value='2'>Option 2</option>
<option value='3'>Option 3</option>
<option value='4'>Option 4</option>
<option value='5'>Option 5</option>
<option value='6'>Option 6</option>
<option value='7'>Option 7</option>
<option value='8'>Option 8</option>
<option value='9'>Option 9</option>
</select>
<input id="btn2" type=button value='Select 2' />
<input id="btn3" type=button value='Select 3' />
<input id="btn5" type=button value='Select 5' />

Of course you can
Just use this code to select option 5:
$("#ComboBox").val(5);
example

All you have to do is go around setting the attribute selected to true or selected.
var arrayOfOptions = $('#mySelect option') //will return an array of options in the order they are found
Just iterate over them, something like:
for(var i=0; i<arrayOfOptions.length; i++) {
var opt = arrayOfOptions[i];
//feel free to check the index of i here if you want to set
//a particular index to selected or a range.
//similarly the range can be passed in as a function parameter.
$(opt).attr('selected','selected');
}

If I understand you correctly, you want to select the option with value=5 and mark it selected. If so, this should be it:
$("#selectBox[value='5']").attr('selected', 'selected');
This should also work:
$("#selectBox").attr('value', 5).attr('selected', 'selected');

Related

How can I set the default value for an HTML <select> element with JavaScript?

How to set the 'selected' (default) value for an HTML <select> element with JavaScript. Aka. currently option0 is 'selected', how to run a script to change it to display the value i want?
this for example because that value is previously saved in a database, and i only want it updated if the user actually specifies to do so. But if i don't specify the value (by re-selecting the previous option), saving the 'edit' will overwrite the previous value with the 'default selected' value the <select> is loaded with.
<select id="selector" name="selector">
<option id="option0" value="0" selected=true >default </option>
<option id="option1" value="1">option 1 </option>
<option id="option1" value="2">option 2 </option>
<option id="option1" value="3">option 3 </option>
<option id="option1" value="4">option 4 </option>
</select>
NOTE: Because i lack reputation to add my answer (below) to the general thread on this topic, here the solution i got to using javascript, to set an option to be the option displayed/selected in the selector. This can also be a <%= value %> from a database.
Use value property to set new selected value using JavaScript
document.getElementById('selector').value="2";
<select id="selector" name="selector">
<option id="option0" value="0" selected=true >default </option>
<option id="option1" value="1">option 1 </option>
<option id="option1" value="2">option 2 </option>
<option id="option1" value="3">option 3 </option>
<option id="option1" value="4">option 4 </option>
</select>
<script>
let options = document.getElementsByTagName('option');
for(i=0; i<options.length; i++){
if (options[i].value === "<%= or_some_string %>"){
options[i].selected = true;
}
}
</script>
We get all the options (this is an html collection) and iterate over it to check if any option is equal to the "String" or "<%=string_value_from_database%>". And set it's .selected to true.
NOTE - MAYBE BETTER - DEFFO SHORTER: with help in the comments:
<script>
let to_select = document.getElementById('selector');
to_select.value = "<%= value %>";
</script>
Where to_select.value is either set to the value you want, or to a database value. Do note, you may or may not need the ".." around the value you set, depending on the setup of the <select> and how you stored your data.
use this
document.getElementById("selector").selectedIndex = 3;
original

How to use getElementByID in JavaScript to connect to my HTML drop down box?

I have a drop-down box in HTML showing three options. I am also using javaScript and want to use the getElementById tool to connect the two. However, I only have one ID for the drop-down box. How does javascript recognize that I have three different options?
There's actually a demo on w3schools.com showing exactly what you're asking. To get the number of options, you could do something like
document.getElementById("mySelect").options.length
Here is an example of how to retrieve the value of a dropdown: https://jsfiddle.net/ykcwgnm8/
You use getElementBy* functions to get the element, however value attribute denotes which item is currently selected.
HTML:
<select id="dropdown">
<option value="1">First option</option>
<option value="2">Second option</option>
<option value="3">Third option</option>
</select>
JS:
function onChangeHandler(e)
{
alert("you have selected item with value "+this.value);
}
document.getElementById("dropdown").addEventListener("change", onChangeHandler);
You can listen for change like this
var list = document.getElementById("mySelect")
list.addEventListener('change', function(e){
console.log(e.target.selectedIndex)
console.log(e.target.options[e.target.selectedIndex].text)
})
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
You can do something like this, here is an example:-
html
<select id="selectBox">
<option value="1">option 1</option>
<option value="2" selected="selected">option 2</option>
<option value="3">option 3</option>
</select>
js
var e = document.getElementById("selectBox");
var selectedValue = e.options[e.selectedIndex].value;
// this will give selectedValue as 2
Hope you find this useful!!

Change "value" of combobox option JS

So, as the title says I want to change the value of a certain option using JS. I have already looked for it but every answer refers to changing the selected option not the value of a specifical option.
<select class="form-control">
<option value="0" selected>Ver</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
</select>
I want to change "Ver" option value from 0 to 1. I don´t know if it is possible but thanks in advance.
Have you tried assigning it an id and then changing it in your js file?
Something like this:
<option value='0' id='opt1' selected>Ver</option>
and in javascript:
document.getElementById("opt1").value = "1";
You can select the option with value 0 using
let opt = document.querySelector('select.form-control option[value="0"]')
You can then change the value by reassigning it
opt.setAttribute('value', '1')
If you have more than one select with class form-control this could be a problem, and you might want to give it/them a unique id — then the selector would be
let opt = document.querySelector('select#your-id option[value="0"]')
Here is a stack snippet doing this, where I've combined the select and the assignment into a single statement. I've also added a change event listener to show the value in the console, so if you switch to 20 then switch to Ver again it would print 20 and then 1 to the console, showing you that the value is indeed 1, not 0
document.querySelector('select.form-control')
.addEventListener('change', function(e) {
console.log(this.value);
});
document.querySelector('select.form-control option[value="0"]')
.setAttribute('value', '1');
select {
min-width: 10em;
}
<select class="form-control">
<option value="0" selected>Ver</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="20">20</option>
<option value="50">50</option>
</select>
Hello you can assign the value with the following instruction
$("#SelectID").val("value option");
document.getElementById("SelectID").value = "value option";
reference in this url Set value of combobox or select

Get a select box by name and set another select box by same name?

I am building a fairly complex form-- I need to copy some data between one and another and I am using jQuery to do this. The only road block I am running into is setting the state.
I have two drop downs, one us using the full state name as the value and the other is using the state abbreviation as the value. The names are the same-
so on form 1 it looks like
<option value="Illinois">Illinois</option>
and form 2 it looks like
<option value="IL">Illinois</option>
Each form has its own unique css selector. How can I set the selected value of form 2 to match what is in form 1 using jQuery?
I do not have any control over the forms, just need to manipulate the input. Have tried using a name selector in jQuery, but I'm not having any luck.
Thank you.
You can do something like this
<select id="fullName">
<option value="Maryland" data-abbr="MD">Maryland</option>
<option value="Illinois" data-abbr="IL">Illinois</option>
<option value="Delaware" data-abbr="DE">Delaware</option>
</select>
<select id="abbr">
<option value="MD">Maryland</option>
<option value="IL">Illinois</option>
<option value="DE">Delaware</option>
</select>
And your jQuery
$('body').on('change', '#fullName', function(){
var abbr = $(this).find('option:selected').data('abbr');
$('#abbr').val(abbr);
});
Try this
<form id="form1" name="form1">
<select name="states" onchange="changeselect(this)">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
<option value="option5">option5</option>
</select>
</form>
<form id="form2" name="form2">
<select name="states">
<option value="opt1">option1</option>
<option value="opt2">option2</option>
<option value="opt3">option3</option>
<option value="opt4">option4</option>
<option value="opt5">option5</option>
</select>
</form>
function changeselect(elem)
{
var value1 = $(elem).val();
$('#form2 select option').removeAttr('selected');
$('#form2').find('select option').each(function(){
var value2 = $(this).html();
if(value1 == value2)
{
var selected = $(this).attr('value');
$('#form2 select').val(selected);
}
});
}
If you create 2 arrays which exactly correspond with one another:
var StateNames = ['Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio','Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming'];
var StateAbbreviations = ['AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY'];
You can:
get the value from the first option list;
find that value's index in the first array; (hint: use indexOf)
use the same index to find out what the corresponding abbreviation is in the second array;
use the returned abbreviation to locate the correct option in the second option list

How to remove/hide select options from select-list

I've got a select list like this:
<select id="selectlist" name="selectproduct" >
<option value=""> --- Select product --- </option>
<option value="1">Product 1</option>
<option value="2">Product 2</option>
<option value="3">Product 3</option>
<option value="4">Product 4</option>
</select>
Unfortunately I can't edit it.
Is there any method which let me hide the "Product 4" option by default?
I'm trying with CSS, but it doesn't work with IE.
To hide it, wrap it with a span tag.
$( "#selectlist option[value=4]" ).wrap( "<span>" );
To show it, unwrap the span tag if it has one.
if ( $( "#selectlist option[value=4]" ).parent().is( "span" ) ){
$( "#selectlist option[value=4]" ).unwrap();
}
using css to hide options is not supported in IE, so you need to update the options list itself.
Try something like
$('#selectlist option[value=4]').remove();
Demo: Fiddle
or if you want to enable it later
var sel = $('#selectlist');
var opts = sel.find('option');
$(':checkbox').click(function(){
sel.empty().append(this.checked ? opts : opts.filter('[value!=4]'));
}).click()
Demo: Fiddle
You can hide option using following line include in scripting.
$("#selectlist option[value='4']").hide();
And if you want to again show this option use following line.
$("#selectlist option[value='4']").show();
To save your time, please read the following answer.
OK, I searched for a few hours and I noticed that there is NO WORKING WAY to "hide" (what I mean is make the option temporally disappeared from the drop-down list) for all browsers, such as set the visibility to be hidden or style="display: none".
My final approach is:
1. Create an array to store all the options for the dropdown list.
2. Use a method to dynamically update the drop-down list according what you want to be shown.
That's it, if you want to use a drop down list without using any library
You can "hide" the option by moving it to a hidden select element or cached document fragment, then move it back when you want to show it:
var selectTool = (function() {
var frag = document.createDocumentFragment();
return {
hideOpt: function (selectId, optIndex) {
var sel = document.getElementById(selectId);
var opt = sel && sel[optIndex];
console.log(opt);
if (opt) {
frag.appendChild(opt);
}
},
showOpt: function (selectId) {
var sel = document.getElementById(selectId);
var opt = frag.firstChild;
if (sel && opt) {
sel.appendChild(opt);
}
}
}
}());
Then you can hide the 4th option like:
<input type="button" value="Hide option" onclick="
selectTool.hideOpt('selectlist',4);
">
and show it again using:
<input type="button" value="Show option" onclick="
selectTool.showOpt('selectlist');
">
All play code of course, but you should get some ideas. If you want to store many options, you'll need a way of referencing them so maybe store them in an object with some form of referencing scheme.
Try to disable that option with disabled attribute.
<select id="selectlist" name="selectproduct" >
<option value=""> --- Select product --- </option>
<option value="1">Product 1</option>
<option value="2">Product 2</option>
<option value="3">Product 3</option>
<option value="4" disabled="disabled">Product 4</option>
</select>
Check demo
see this link
http://jsfiddle.net/DKKMN/
<select id="selectlist" name="selectproduct" >
<option value=""> --- Select product --- </option>
<option value="1">Product 1</option>
<option value="2">Product 2</option>
<option value="3">Product 3</option>
<option value="4" id="i">Product 4</option>
</select>
#i{display:none;}
create an id and in style make it invisble
I suppose you are using JQuery as well.
$("#selectlist option[value='option4']").remove();
to append the child below the list of option using java script.
`var option = document.createElement("option");
option.text = "All Users";
option.value = "all_user";
var select = document.getElementById("log_user_type");
select.appendChild(option);`
if you want to remove some option from select list you can use this code:
<script type="text/javascript">
$(window).bind("load", function() {
$('#select_list_id option[value="AB"],option[value="SK"]').remove();
});
</script>
<option value="4" style="display:none">Product 4</option>
hides the 4th option by default.

Categories

Resources