I have a HTML select list, which can have multiple selects:
<select id="mySelect" name="myList" multiple="multiple" size="3">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option> `
<option value="4">Fourth</option>
...
</select>
I want to get an option's text everytime i choose it. I use jQuery to do this:
$('#mySelect').change(function() {
alert($('#mySelect option:selected').text());
});
Looks simple enough, however if select list has already some selected options - it will return their text too. As example, if i had already selected the "Second" option, after choosing "Fourth" one, alert would bring me this - "SecondFourth". So is there any short, simple way with jQuery to get only the "current" selected option's text or do i have to play with strings and filter new text?
You could do something like this, keeping the old value array and checking which new one isn't in there, like this:
var val;
$('#mySelect').change(function() {
var newVal = $(this).val();
for(var i=0; i<newVal.length; i++) {
if($.inArray(newVal[i], val) == -1)
alert($(this).find('option[value="' + newVal[i] + '"]').text());
}
val = newVal;
});
Give it a try here, When you call .val() on a <select multiple> it returns an array of the values of its selected <option> elements. We're simply storing that, and when the selection changes, looping through the new values, if the new value was in the old value array ($.inArray(val, arr) == -1 if not found) then that's the new value. After that we're just using an attribute-equals selector to grab the element and get its .text().
If the value="" may contains quotes or other special characters that would interfere with the selector, use .filter() instead, like this:
$(this).children().filter(function() {
return this.value == newVal[i];
}).text());
Set a onClick on the option instead of the select:
$('#mySelect option').click(function() {
if ($(this).attr('selected')) {
alert($(this).val());
}
});
var val = ''
$('#mySelect').change(function() {
newVal = $('#mySelect option:selected').text();
val += newVal;
alert(val); # you need this.
val = newVal;
});
or let's play some more
val = '';
$('#id_timezone')
.focus(
function(){
val = $('#id_timezone option:selected').text();
})
.change(
function(){
alert(val+$('#id_timezone option:selected').text())
});
Cheers.
This question already has answers here:
Changing the selected option of an HTML Select element
(14 answers)
Closed 5 years ago.
I try a several ways to make it, but only what I got - two selected items in one time. Also I found on SOF a "solution" - document.getElementById("selection-type").selectedIndex = 2; , but it does not work.
I understand that this is a very simple question, but I really do not know what is I'am missed.
var select = document.body.querySelector('select');
for (var i = 0; i < select.options.length; i++) {
if (select.options[i].selected) {
}
}
select.options[1].selected = false;
var newOption = new Option('Classic', 'Classic');
select.append(newOption);
select.options[2].selected = true;
<select>
<option value="Rock">Storm</option>
<option value="Blues" selected>Rain</option>
</select>
You are confusing attributes and properties. Changing a property is a dynamic action that affects the in-memory object, it doesn't modify the static HTML that the element was originally parsed with. If you want to change the attribute, you need to use setAttribute() or removeAttribute().
var select = document.body.querySelector('select');
// Get the element with the "selected" attribute
console.log("Element with 'selected' HTML attribute: " +
select.querySelector("[selected]").getAttribute("value"));
// Get the element with the "selected" value:
console.log("Element with value property of 'selected': " + select.value);
// Change the value property of the select
console.log("Changing value of select element to 'Rock'");
select.value = "Rock";
// Get the element with the "selected" attribute
console.log("Element with 'selected' HTML attribute: " +
select.querySelector("[selected]").getAttribute("value")); // Still Blues!
// Get the element with the "selected" value:
console.log("But, value of the select element is now: " + select.value); // Now Rock!
// Change which element has the selected attribute
console.log("Switching elment that has the 'selected' attribute...");
select.querySelector("[selected]").removeAttribute("selected");
select.querySelector("[value=Rock]").setAttribute("selected", "selected");
console.log("Element with 'selected' HTML attribute: " +
select.querySelector("[selected]").getAttribute("value"));
console.log(select.options[0])
console.log(select.options[1]);
<select>
<option value="Rock">Storm</option>
<option value="Blues" selected>Rain</option>
</select>
To answer the question in the title, all you need to do is set the desired option as selected. To get current <select> value one should look into the select.value:
let select = document.body.querySelector('select'),
newOption = new Option('Classic', 'Classic');
select.append(newOption);
select.options[2].selected = true;
console.log(select.value);
// Classic
<select>
<option value="Rock">Storm</option>
<option value="Blues" selected>Rain</option>
</select>
Also note selected attribute only marks default selection, and is different than the selected property of the <option>. The attribute simply tells the browser if it should render the option as selected when initially drawing the DOM element or not.
When dealing with <select multiple>, you need to check the .selectedOptions property of the <select> and map it to an array. Example:
let select = document.body.querySelector('select'),
newOption = new Option('Classic', 'Classic');
select.append(newOption);
select.options[2].selected = true;
let values = [].slice.call(select.selectedOptions).map(a => a.value);
console.log(values)
// ["Blues","Classic"]
<select multiple>
<option value="Rock">Storm</option>
<option value="Blues" selected>Rain</option>
</select>
The .selectedOptions is an object which contains the selected options, the length and native methods, such as item() and namedItem(). Do note option groups are not contained.
I have a dropdown list
<select name="answers[0][]">
<option value="0" >Beredskap</option>
<option value="1" >Förbundsledning</option>
<option value="2" >Förbundsledning stab</option>
<option value="3" >Ekonomiavdelningen</option>
</select>
What i am seeking for is to get the value getElementsByTagName('select')[1] and then replace it with
<option value="1" disabled >Förbundsledning</option>
the reason for it is that the list is auto generated so i need to modify the html output instead.
what i have sofar that does not work is :
document.getElementsByTagName('select')[0]
.innerHTML.replace('<option value="1" disabled>apple</option>')
The option with the value 1 happens to be at index 1 in your code, should that always be the case other answers than this one will apply.
In the case where you don't know the order of the generated options and thus don't know the index of the option you want to change, it depends on whether you want to change the text based on the value or the original text.
You could do this:
var options = document.getElementsByTagName("option");
for(var e = 0; e < options.length; e++) {
//change by text
if (options[e].text == "Apple") {
options[e].text = "Förbundsledning";
}
//change by value
if (options[e].value == "1") {
options[e].text = "Förbundsledning";
}
}
you could use jQuery and selectors to find your list box $('#myListBox').val();
you can easily change the value by $('#myListBox').val("new value");
You can also easily iterate over the list of options and do whatever you wish.
$("#id option").each(function()
{
// add $(this).val() to your list
});
How about this ?
var sel = document.getElementsByTagName('select')[0];
sel.innerHTML = sel.innerHTML.replace('Förbundsledning', 'apple');
http://jsfiddle.net/VxhvF/
use function ;
function select_text_replace(option_text, replace_text) {
var el = document.getElementsByTagName('select')[0];
el.innerHTML = el.innerHTML.replace(option_text, replace_text);
};
select_text_replace("Förbundsledning", "apple");
select_text_replace("Ekonomiavdelningen", "apple2");
see sample: http://jsfiddle.net/sm94N/
document.getElementsByTagName('select')[0].options[1].text="apple"
[1] is index of your options item. 0 = Beredskap, 1 = Förbundsledning.
Below are the options that I have in my HTML code:
<label id="subn">
<select name="subs" id="subs">
<option value="nothing">Choose a Subject</option>
<option value="General Question">General Question</option>
<option value="MemberShip Area">MemberShip Area</option>
<option value="Others">Others</option>
</select>
</label>
I want to create JavaScript code that will check whether the user selected an option other than the first one.
Here is what I tried:
if (document.getElementsByTagName('option') == "nothing"){
document.getElementById("subn").innerHTML = "Subject is Required!";
document.getElementById("subs").focus();
return false;
}
You can check like this if nothing is the first option (usually the case in my experience):
if (document.getElementById('subs').selectedIndex == 0){
To still compare based on the value, do this:
var sel = document.getElementById('subs');
if (sel.options[sel.selectedIndex].value == 'nothing') {
You may want to change your markup so the label is beside, like this:
<select name="subs" id="subs"></select><label id="subn" for="subs"></label>
Otherwise this part: .innerHTML = "Subject is Required!"; will erase your <select> :)
This should do it:
var index = document.your_form_name.subs.selectedIndex;
var value = document.your_form_name.subs.options[index].value;
if (value === "nothing"){
// your further code here.........
}
document.getElementsByTagName('option') gives a collection of all option elements in the document and "nothing" is a string. Comparing a collection to a string is quite useless.
Also setting document.getElementById("subn").innerHTML = "Subject is Required!"; will delete the select element, so document.getElementById("subs") wouldn't find anything any more.
If you just need to know if anything is selected check the selectedIndex property of the select element:
if (document.getElementById("subs").selectedIndex <= 0) {
// nothing is selected
}
EDIT: Changed > 0 to <= 0. I would assume that it should be checked if the user didn't select anything, too.
Using core jQuery, how do you remove all the options of a select box, then add one option and select it?
My select box is the following.
<Select id="mySelect" size="9"> </Select>
EDIT: The following code was helpful with chaining. However, (in Internet Explorer) .val('whatever') did not select the option that was added. (I did use the same 'value' in both .append and .val.)
$('#mySelect').find('option').remove().end()
.append('<option value="whatever">text</option>').val('whatever');
EDIT: Trying to get it to mimic this code, I use the following code whenever the page/form is reset. This select box is populated by a set of radio buttons. .focus() was closer, but the option did not appear selected like it does with .selected= "true". Nothing is wrong with my existing code - I am just trying to learn jQuery.
var mySelect = document.getElementById('mySelect');
mySelect.options.length = 0;
mySelect.options[0] = new Option ("Foo (only choice)", "Foo");
mySelect.options[0].selected="true";
EDIT: selected answer was close to what I needed. This worked for me:
$('#mySelect').children().remove().end()
.append('<option selected value="whatever">text</option>') ;
But both answers led me to my final solution..
$('#mySelect')
.find('option')
.remove()
.end()
.append('<option value="whatever">text</option>')
.val('whatever')
;
$('#mySelect')
.empty()
.append('<option selected="selected" value="whatever">text</option>')
;
why not just use plain javascript?
document.getElementById("selectID").options.length = 0;
If your goal is to remove all the options from the select except the first one (typically the 'Please pick an item' option) you could use:
$('#mySelect').find('option:not(:first)').remove();
I had a bug in IE7 (works fine in IE6) where using the above jQuery methods would clear the select in the DOM but not on screen. Using the IE Developer Toolbar I could confirm that the select had been cleared and had the new items, but visually the select still showed the old items - even though you could not select them.
The fix was to use standard DOM methods/properites (as the poster original had) to clear rather than jQuery - still using jQuery to add options.
$('#mySelect')[0].options.length = 0;
Not sure exactly what you mean by "add one and select it", since it will be selected by default anyway. But, if you were to add more than one, it would make more sense. How about something like:
$('select').children().remove();
$('select').append('<option id="foo">foo</option>');
$('#foo').focus();
Response to "EDIT": Can you clarify what you mean by "This select box is populated by a set of radio buttons"? A <select> element cannot (legally) contain <input type="radio"> elements.
$('#mySelect')
.empty()
.append('<option value="whatever">text</option>')
.find('option:first')
.attr("selected","selected")
;
$("#control").html("<option selected=\"selected\">The Option...</option>");
Just one line to remove all options from the select tag and after you can add any options then make second line to add options.
$('.ddlsl').empty();
$('.ddlsl').append(new Option('Select all', 'all'));
One more short way but didn't tried
$('.ddlsl').empty().append(new Option('Select all', 'all'));
Thanks to the answers I received, I was able to create something like the following, which suits my needs. My question was somewhat ambiguous. Thanks for following up. My final problem was solved by including "selected" in the option that I wanted selected.
$(function() {
$('#mySelect').children().remove().end().append('<option selected value="One">One option</option>') ; // clear the select box, then add one option which is selected
$("input[name='myRadio']").filter( "[value='1']" ).attr( "checked", "checked" ); // select radio button with value 1
// Bind click event to each radio button.
$("input[name='myRadio']").bind("click",
function() {
switch(this.value) {
case "1":
$('#mySelect').find('option').remove().end().append('<option selected value="One">One option</option>') ;
break ;
case "2":
$('#mySelect').find('option').remove() ;
var items = ["Item1", "Item2", "Item3"] ; // Set locally for demo
var options = '' ;
for (var i = 0; i < items.length; i++) {
if (i==0) {
options += '<option selected value="' + items[i] + '">' + items[i] + '</option>';
}
else {
options += '<option value="' + items[i] + '">' + items[i] + '</option>';
}
}
$('#mySelect').html(options); // Populate select box with array
break ;
} // Switch end
} // Bind function end
); // bind end
}); // Event listener end
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>One<input name="myRadio" type="radio" value="1" /></label>
<label>Two<input name="myRadio" type="radio" value="2" /></label>
<select id="mySelect" size="9"></select>
I've found on the net something like below. With a thousands of options like in my situation this is a lot faster than .empty() or .find().remove() from jQuery.
var ClearOptionsFast = function(id) {
var selectObj = document.getElementById(id);
var selectParentNode = selectObj.parentNode;
var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy
selectParentNode.replaceChild(newSelectObj, selectObj);
return newSelectObj;
}
More info here.
$("#id option").remove();
$("#id").append('<option value="testValue" >TestText</option>');
The first line of code will remove all the options of a select box as no option find criteria has been mentioned.
The second line of code will add the Option with the specified value("testValue") and Text("TestText").
Building on mauretto's answer, this is a little easier to read and understand:
$('#mySelect').find('option').not(':first').remove();
To remove all the options except one with a specific value, you can use this:
$('#mySelect').find('option').not('[value=123]').remove();
This would be better if the option to be added was already there.
How about just changing the html to new data.
$('#mySelect').html('<option value="whatever">text</option>');
Another example:
$('#mySelect').html('
<option value="1" selected>text1</option>
<option value="2">text2</option>
<option value="3" disabled>text3</option>
');
Another way:
$('#select').empty().append($('<option>').text('---------').attr('value',''));
Under this link, there are good practices https://api.jquery.com/select/
First clear all exisiting option execpt the first one(--Select--)
Append new option values using loop one by one
$('#ddlCustomer').find('option:not(:first)').remove();
for (var i = 0; i < oResult.length; i++) {
$("#ddlCustomer").append(new Option(oResult[i].CustomerName, oResult[i].CustomerID + '/' + oResult[i].ID));
}
Uses the jquery prop() to clear the selected option
$('#mySelect option:selected').prop('selected', false);
This will replace your existing mySelect with a new mySelect.
$('#mySelect').replaceWith('<Select id="mySelect" size="9">
<option value="whatever" selected="selected" >text</option>
</Select>');
You can do simply by replacing html
$('#mySelect')
.html('<option value="whatever" selected>text</option>')
.trigger('change');
I saw this code in Select2 -
Clearing Selections
$('#mySelect').val(null).trigger('change');
This code works well with jQuery even without Select2
Cleaner give me Like it
let data= []
let inp = $('#mySelect')
inp.empty()
data.forEach(el=> inp.append( new Option(el.Nombre, el.Id) ))
save the option values to be appended in an object
clear existing options in the select tag
iterate the list object and append the contents to the intended select tag
var listToAppend = {'':'Select Vehicle','mc': 'Motor Cyle', 'tr': 'Tricycle'};
$('#selectID').empty();
$.each(listToAppend, function(val, text) {
$('#selectID').append( new Option(text,val) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I used vanilla javascript
let select = document.getElementById("mySelect");
select.innerHTML = "";
Hope it will work
$('#myselect').find('option').remove()
.append($('<option></option>').val('value1').html('option1'));
var select = $('#mySelect');
select.find('option').remove().end()
.append($('<option/>').val('').text('Select'));
var data = [{"id":1,"title":"Option one"}, {"id":2,"title":"Option two"}];
for(var i in data) {
var d = data[i];
var option = $('<option/>').val(d.id).text(d.title);
select.append(option);
}
select.val('');
Try
mySelect.innerHTML = `<option selected value="whatever">text</option>`
function setOne() {
console.log({mySelect});
mySelect.innerHTML = `<option selected value="whatever">text</option>`;
}
<button onclick="setOne()" >set one</button>
<Select id="mySelect" size="9">
<option value="1">old1</option>
<option value="2">old2</option>
<option value="3">old3</option>
</Select>
The shortest answer:
$('#mySelect option').remove().append('<option selected value="whatever">text</option>');
Try
$('#mySelect')
.html('<option value="whatever">text</option>')
.find('option:first')
.attr("selected","selected");
OR
$('#mySelect').html('<option value="4">Value 4</option>
<option value="5">Value 5</option>
<option value="6">Value 6</option>
<option value="7">Value 7</option>
<option value="8">Value 8</option>')
.find('option:first')
.prop("selected",true);