JavaScript: How to modify value in <option> - javascript

How do I modify a value of <option>?
I've tried:
var example = document.getElementById("test"); // This is the <option>
example.value = "Test";
The code above doesn't modify anything.
However, if the code above modifies a value of <select>'s displayed value, the value goes blank;

Use example.textContent to change the value that's displayed. The value that is displayed when an option element is selected is its text content.
However, as indicated in Oriol's answer, changing the value property is meaningful, even if it is not immediately visible.
document.getElementById("change").onclick = function () {
var option = document.getElementById("test");
option.textContent = "bon soir";
option.value = "les étoiles sont belles, hein?";
}
document.getElementById("selector").onchange = function() {
// in this line "this" refers to the <select> element
document.getElementById("selection").textContent = this.value;
}
<select id="selector">
<option></option>
<option id="test" value="good to see you">hello</option>
<option value="see you again">goodbye</option>
</select>
<input type="button" id="change" value="Change value" />
<div id="selection"></div>

The value of an option and its text are different things.
Its value will become, when selected, the value of the select, and will be sent to the server when submitting the form. Analogously, when you set select's value, the selected option will be the one that has that value.
What you want to change is its text, e.g. with one of these:
option.textContent = "Test";
option.innerHTML = "Test";

In realy, you need to see how option element sintax.
<option value="my_value">The Label</option>
So, you need to change the textContent instead value. See the sample below.
document.getElementById('change').onclick = function () {
document.getElementById('my_option').textContent = 'My New Label';
document.getElementById('my_option').value = 'my_new_value';
}
<select>
<option id="my_option" value="my_value">My Label</option>
</select>
<button id="change" type="button">change</button>
The first changes the label (a nicename for the user) and the second changes the value sended to server.

Related

How can I get the value of a custom attribute in a dropdownlist using javascript or jquery

I have dropdownlist on a webform. I need a 'hidden' variable per item in the dropdown list which I can retrieve clientside using the onchange event.
So on the page load I'm setting a custom attribute after I databind the dropdownlist:
For i = 0 To cboNameAL.Items.Count - 1
cboNameAL.Items(i).Attributes.Add("Charge_Rate", usernamesAdapterDataTable.Item(i).ChargeRate)
Next
This works and when I look at my rendered page I see this markup for each item in the dropdownlist
<option value="05ab8c45-f7ce-4250-8458-1421e79e8a51" charge_rate="32">dave</option>
My javascript function is firing fine from the onchange event, however I can't retrieve the attribute value for Charge_Rate.
I've tried every combination of:
var lCharge_Rate = document.getElementById("<%=cboNameAL.ClientID%>").selectedItem.attributes('Charge_Rate');
var lCharge_Rate = document.getElementById("<%=cboNameAL.ClientID%>").attributes('Charge_Rate');
var lCharge_Rate = document.getElementById("<%=cboNameAL.ClientID%>")attr('Charge_Rate');
var lCharge_Rate = document.getElementById("<%=cboNameAL.ClientID%>").getAttributes('Charge_Rate');
Each with either ('Charge_Rate') or ("Charge_Rate") or .Charge_Rate
I've debugged and the best I can do is for my variable lCharge_Rate to be null.
Any ideas? Happy to rework if it can't be done this way...
You can use the following code to get the value of your custom attribute
//This line will load the DOM of dropdown
var cboNameAL = document.getElementById("<%=cboNameAL.ClientID%>");
//This will return the selected option
var selectedOption = cboNameAL.options[cboNameAL.selectedIndex];
//This will give you the value of the attribut
var charge_rate = selectedOption.attributes.charge_rate.value;
You need to select the options first before you can get the attribute.
var e = document.getElementById("client_id"),
lCharge_Rate = e.options[e.selectedIndex].getAttribute('charge_rate');
document.write("Charge Rate = "+lCharge_Rate);
<select id="client_id">
<option value="05ab8c45-f7ce-4250-8458-1421e79e8a51" charge_rate="32">dave</option>
</select>
Create a variable that equals the value of your custom attribute, then use it as you desire. See my example and adjust as needed.
var $divAtribut = $("div").attr("Charge_Rate");
alert($divAtribut);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div Charge_Rate="4424">Click on run to get the attribute</div>
<code>
<!– my html –>
<select name="custom-select-two">
<option value="1" data-monthvalue="31">Jan</option>
<option value="2" data-monthvalue="28">Feb</option>
<option value="3" data-monthvalue="31">Mar</option>
<option value="4" data-monthvalue="30">Apr</option>
<option value="5" data-monthvalue="31">May</option>
<select>
<!– Get value of option’s custom attribute value from dropdown or select box –>
<script type="text/javascript">
$(document).ready(function(){
var monthvalue = $('.custom-select-two :selected').data('monthvalue');
alert(monthvalue); // here comes your dropdown option's custom attribute value
});
</script>
</code>

How to assign user selection to a javascript variable?

I have a basic HTML form list:
<select name="sites" id="sites">
<option value="http://www.google.com">Google</option>
<option value="http://www.bing.com">Bing</option>
<option value="http://www.yahoo.com">Yahoo</option>
</select>
I want to be able to assign a string to a variable depending on the user section, e.g. if Google is selected the JS var 'link' equals 'abc'.
I understand how to assign the value to the variable, but not sure on assigning a string of text.
Would this be along the lines of a if statement;
if sites = 'http://www.google.com' then var link = 'abc'?
You need to check onchange event, then it's simply:
var select = document.getElementById('sites');
var str;
sites.onchange = function() {
str = this.value;
alert(str);
}
http://jsfiddle.net/oLz2wkLb/

How to get the id dropdown list on click event

This is my jspPage.
<select id="class_Teacher" name="classTeacher" style="height:25px; width: 190px;" onchange="Class(this.id)">
<option id="1">Manager</option>
<option id="2">Supervisor</option>
</select>
And here is javascript
function Class(str)
{
alert(str);
}
i want to get the id of Option on onchange Event. Thanks :)
You can do this if you are trying to get the id of the option which has been selected
function Class(str)
{
var select = document.getElementById("class_Teacher");
var option = select.options[select.selectedIndex];
alert(option.id);
}
Your onchange event will look like this. Just remove the .id as that will return the id of the select box itself not the option
onchange="myFunction(this)"
and your javascript function like this, which will alert the ID of the selected option
function myFunction(ele){
alert(ele.options[ele.selectedIndex].id);
}
Broken down ele represents the select box (a dom object). .options accesses the options within the select box. the [] brackets are a way of accessing a specific option. Like an array myArr[1] etc. and ele.selectedIndex returns a number representing the selected option i.e if the first option is chosen - ele.selectedIndex will be equivalent to 0.
HTML (you should use "value" attribute instead of "id")
<select id="class_Teacher" name="classTeacher" style="height:25px; width: 190px;" onchange="onChange()">
<option id="1" value="ID1">Manager</option>
<option id="2" value="ID2">Supervisor</option>
</select>
JS
var selectElement = document.getElementById("class_Teacher");
selectElement.onchange=function(){
alert(selectElement.options[selectElement.selectedIndex].id); // id in the html element
alert(selectElement.selectedIndex); // index starting from 0
alert(selectElement.value); // value of the selected element
};
Fiddle
Use selsectedIndex Property of GetElementByID
<script>
function val() {
d = document.getElementById("select_id").selectedIndex;
alert(d);
}
</script>
<select onchange="val()" id="select_id">

Set variable value from input before submit

First, I have this input in a form.
<select id="entry_14">
<option value="Woman">Woman</option>
<option value="Man">Man</option>
</select>
Then I declared this variable.
var mygender = document.getElementById('entry_14').value;
but then, when I document.write, it already shows "Man" before the user even makes a selection, and after selecting woman, it still shows man.
How can I set the value of this variable to change, each time the user selects one of the options?
It executes immediately because your code is not in a function. You need to call this function when the select changes. Add an onchange handler to your select. In this example I pass this.value which is your select lists value to the function. Finally you can do whatever you want with that value.
<select id="entry_14" onchange="myfunction(this.value);">
<option value="Woman">Woman</option>
<option value="Man">Man</option>
</select>
<script>
function myfunction(val) {
document.write(val);
}
</script>
Declare a onchange event handler.
document.getElementById('entry_14').onchange = function(){
var mygender = this.value;
document.write(mygender);
}
Add a onChange JS handler to the <select> element. The example below shows an inline way of doing this...
<select id="entry_14" onChange="updateMyGender();">
....
</select>
<script>
var mygender = document.getElementById('entry_14').value;
function updateMyGender()
{
mygender = document.getElementById('entry_14').value;
}
</script>
I think you are looking for this
var mygender= document.getElementById('entry_14');
var gender= mygender.options[mygender.selectedIndex].value;// for value
var gender= mygender.options[mygender.selectedIndex].Text;//for text

set option "selected" attribute from dynamic created option

I have a dynamically created select option using a javascript function. the select object is
<select name="country" id="country">
</select>
when the js function is executed, the "country" object is
<select name="country" id="country">
<option value="AF">Afghanistan</option>
<option value="AL">Albania</option>
...
<option value="ID">Indonesia</option>
...
<option value="ZW">Zimbabwe</option>
</select>
and displaying "Indonesia" as default selected option. note : there is no selected="selected" attribute in that option.
then I need to set selected="selected" attribute to "Indonesia", and I use this
var country = document.getElementById("country");
country.options[country.options.selectedIndex].setAttribute("selected", "selected");
using firebug, I can see the "Indonesia" option is like this
<option value="ID" selected="selected">Indonesia</option>
but it fails in IE (tested in IE 8).
and then I have tried using jQuery
$( function() {
$("#country option:selected").attr("selected", "selected");
});
it fails both in FFX and IE.
I need the "Indonesia" option to have selected="selected" attribute so when I click reset button, it will select "Indonesia" again.
changing the js function to dynamically create "country" options is not an option. the solution must work both in FFX and IE.
thank you
You're overthinking it:
var country = document.getElementById("country");
country.options[country.options.selectedIndex].selected = true;
Good question. You will need to modify the HTML itself rather than rely on DOM properties.
var opt = $("option[val=ID]"),
html = $("<div>").append(opt.clone()).html();
html = html.replace(/\>/, ' selected="selected">');
opt.replaceWith(html);
The code grabs the option element for Indonesia, clones it and puts it into a new div (not in the document) to retrieve the full HTML string: <option value="ID">Indonesia</option>.
It then does a string replace to add the attribute selected="selected" as a string, before replacing the original option with this new one.
I tested it on IE7. See it with the reset button working properly here: http://jsfiddle.net/XmW49/
Instead of modifying the HTML itself, you should just set the value you want from the relative option element:
$(function() {
$("#country").val("ID");
});
In this case "ID" is the value of the option "Indonesia"
So many wrong answers!
To specify the value that a form field should revert to upon resetting the form, use the following properties:
Checkbox or radio button: defaultChecked
Any other <input> control: defaultValue
Option in a drop down list: defaultSelected
So, to specify the currently selected option as the default:
var country = document.getElementById("country");
country.options[country.selectedIndex].defaultSelected = true;
It may be a good idea to set the defaultSelected value for every option, in case one had previously been set:
var country = document.getElementById("country");
for (var i = 0; i < country.options.length; i++) {
country.options[i].defaultSelected = i == country.selectedIndex;
}
Now, when the form is reset, the selected option will be the one you specified.
// get the OPTION we want selected
var $option = $('#SelectList').children('option[value="'+ id +'"]');
// and now set the option we want selected
$option.attr('selected', true);​​
What you want to do is set the selectedIndex attribute of the select box.
country.options.selectedIndex = index_of_indonesia;
Changing the 'selected' attribute will generally not work in IE. If you really want the behavior you're describing, I suggest you write a custom javascript reset function to reset all the other values in the form to their default.
This works in FF, IE9
var x = document.getElementById("country").children[2];
x.setAttribute("selected", "selected");
Make option defaultSelected
HTMLOptionElement.defaultSelected = true; // JS
$('selector').prop({defaultSelected: true}); // jQuery
HTMLOptionElement MDN
If the SELECT element is already added to the document (statically or dynamically), to set an option to Attribute-selected and to make it survive a HTMLFormElement.reset() - defaultSelected is used:
const EL_country = document.querySelector('#country');
EL_country.value = 'ID'; // Set SELECT value to 'ID' ("Indonesia")
EL_country.options[EL_country.selectedIndex].defaultSelected = true; // Add Attribute selected to Option Element
document.forms[0].reset(); // "Indonesia" is still selected
<form>
<select name="country" id="country">
<option value="AF">Afghanistan</option>
<option value="AL">Albania</option>
<option value="HR">Croatia</option>
<option value="ID">Indonesia</option>
<option value="ZW">Zimbabwe</option>
</select>
</form>
The above will also work if you build the options dynamically, and than (only afterwards) you want to set one option to be defaultSelected.
const countries = {
AF: 'Afghanistan',
AL: 'Albania',
HR: 'Croatia',
ID: 'Indonesia',
ZW: 'Zimbabwe',
};
const EL_country = document.querySelector('#country');
// (Bad example. Ideally use .createDocumentFragment() and .appendChild() methods)
EL_country.innerHTML = Object.keys(countries).reduce((str, key) => str += `<option value="${key}">${countries[key]}</option>`, '');
EL_country.value = 'ID';
EL_country.options[EL_country.selectedIndex].defaultSelected = true;
document.forms[0].reset(); // "Indonesia" is still selected
<form>
<select name="country" id="country"></select>
</form>
Make option defaultSelected while dynamically creating options
To make an option selected while populating the SELECT Element, use the Option() constructor MDN
var optionElementReference = new Option(text, value, defaultSelected, selected);
const countries = {
AF: 'Afghanistan',
AL: 'Albania',
HR: 'Croatia',
ID: 'Indonesia', // <<< make this one defaultSelected
ZW: 'Zimbabwe',
};
const EL_country = document.querySelector('#country');
const DF_options = document.createDocumentFragment();
Object.keys(countries).forEach(key => {
const isIndonesia = key === 'ID'; // Boolean
DF_options.appendChild(new Option(countries[key], key, isIndonesia, isIndonesia))
});
EL_country.appendChild(DF_options);
document.forms[0].reset(); // "Indonesia" is still selected
<form>
<select name="country" id="country"></select>
</form>
In the demo above Document.createDocumentFragment is used to prevent rendering elements inside the DOM in a loop. Instead, the fragment (containing all the Options) is appended to the Select only once.
SELECT.value vs. OPTION.setAttribute vs. OPTION.selected vs. OPTION.defaultSelected
Although some (older) browsers interpret the OPTION's selected attribute as a "string" state, the WHATWG HTML Specifications html.spec.whatwg.org state that it should represent a Boolean selectedness
The selectedness of an option element is a boolean state, initially false. Except where otherwise specified, when the element is created, its selectedness must be set to true if the element has a selected attribute.
html.spec.whatwg.org - Option selectedness
one can correctly deduce that just the name selected in <option value="foo" selected> is enough to set a truthy state.
Comparison test of the different methods
const EL_select = document.querySelector('#country');
const TPL_options = `
<option value="AF">Afghanistan</option>
<option value="AL">Albania</option>
<option value="HR">Croatia</option>
<option value="ID">Indonesia</option>
<option value="ZW">Zimbabwe</option>
`;
// https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/MutationObserver
const mutationCB = (mutationsList, observer) => {
mutationsList.forEach(mu => {
const EL = mu.target;
if (mu.type === 'attributes') {
return console.log(`* Attribute ${mu.attributeName} Mutation. ${EL.value}(${EL.text})`);
}
});
};
// (PREPARE SOME TEST FUNCTIONS)
const testOptionsSelectedByProperty = () => {
const test = 'OPTION with Property selected:';
try {
const EL = [...EL_select.options].find(opt => opt.selected);
console.log(`${test} ${EL.value}(${EL.text}) PropSelectedValue: ${EL.selected}`);
} catch (e) {
console.log(`${test} NOT FOUND!`);
}
}
const testOptionsSelectedByAttribute = () => {
const test = 'OPTION with Attribute selected:'
try {
const EL = [...EL_select.options].find(opt => opt.hasAttribute('selected'));
console.log(`${test} ${EL.value}(${EL.text}) AttrSelectedValue: ${EL.getAttribute('selected')}`);
} catch (e) {
console.log(`${test} NOT FOUND!`);
}
}
const testSelect = () => {
console.log(`SELECT value:${EL_select.value} selectedIndex:${EL_select.selectedIndex}`);
}
const formReset = () => {
EL_select.value = '';
EL_select.innerHTML = TPL_options;
// Attach MutationObserver to every Option to track if Attribute will change
[...EL_select.options].forEach(EL_option => {
const observer = new MutationObserver(mutationCB);
observer.observe(EL_option, {attributes: true});
});
}
// -----------
// LET'S TEST!
console.log('\n1. Set SELECT value');
formReset();
EL_select.value = 'AL'; // Constatation: MutationObserver did NOT triggered!!!!
testOptionsSelectedByProperty();
testOptionsSelectedByAttribute();
testSelect();
console.log('\n2. Set HTMLElement.setAttribute()');
formReset();
EL_select.options[2].setAttribute('selected', true); // MutationObserver triggers
testOptionsSelectedByProperty();
testOptionsSelectedByAttribute();
testSelect();
console.log('\n3. Set HTMLOptionElement.defaultSelected');
formReset();
EL_select.options[3].defaultSelected = true; // MutationObserver triggers
testOptionsSelectedByProperty();
testOptionsSelectedByAttribute();
testSelect();
console.log('\n4. Set SELECT value and HTMLOptionElement.defaultSelected');
formReset();
EL_select.value = 'ZW'
EL_select.options[EL_select.selectedIndex].defaultSelected = true; // MutationObserver triggers
testOptionsSelectedByProperty();
testOptionsSelectedByAttribute();
testSelect();
/* END */
console.log('\n*. Getting MutationObservers out from call-stack...');
<form>
<select name="country" id="country"></select>
</form>
Although the test 2. using .setAttribute() seems at first the best solution since both the Element Property and Attribute are unison, it can lead to confusion, specially because .setAttribute expects two parameters:
EL_select.options[1].setAttribute('selected', false);
// <option value="AL" selected="false"> // But still selected!
will actually make the option selected
Should one use .removeAttribute() or perhaps .setAttribute('selected', ???) to another value? Or should one read the state by using .getAttribute('selected') or by using .hasAttribute('selected')?
Instead test 3. (and 4.) using defaultSelected gives the expected results:
Attribute selected as a named Selectedness state.
Property selected on the Element Object, with a Boolean value.
select = document.getElementById('selectId');
var opt = document.createElement('option');
opt.value = 'value';
opt.innerHTML = 'name';
opt.selected = true;
select.appendChild(opt);
// Get <select> object
var sel = $('country');
// Loop through and look for value match, then break
for(i=0;i<sel.length;i++) { if(sel.value=="ID") { break; } }
// Select index
sel.options.selectedIndex = i;
Begitu loh.
This should work.
$("#country [value='ID']").attr("selected","selected");
If you have function calls bound to the element just follow it with something like
$("#country").change();
You could search all the option values until it finds the correct one.
var defaultVal = "Country";
$("#select").find("option").each(function () {
if ($(this).val() == defaultVal) {
$(this).prop("selected", "selected");
}
});
Vanilla JS
Use this for Vanilla Javascript, keeping in mind that you can feed the example "numbers" array with any data from a fetch function (for example).
The initial HTML code:
<label for="the_selection">
<select name="the_selection" id="the_selection_id">
<!-- Empty Selection -->
</select>
</label>
Some values select tag:
const selectionList = document.getElementById('the_selection_id');
const numbers = ['1','3','5'];
numbers.forEach(number => {
const someOption = document.createElement('option');
someOption.setAttribute('value', number);
someOption.innerText = number;
if (number == '3') someOption.defaultSelected = true;
selectionList.appendChild(someOption);
})
You'll get:
<label for="the_selection">
<select name="the_selection" id="the_selection_id">
<!-- Empty Selection -->
<option value="1">1</option>
<option value="3" selected>3</option>
<option value="5">5</option>
</select>
</label>
You can solve this on ES6 like this:
var defaultValue = "ID";
[...document.getElementById('country').options].map(e => e.selected = (e.value == defaultValue));
I haven't test in other browsers but in Chrome works just fine.
...document.getElementById('country').options using the spread operator you cast options as an array.
.map allows you to apply a function to each element of your array.
e represents each <option> element of your object so you can access its attributes like .select and .value as getter and setter.
Because you .select receives a boolean option you want to assign when its value is equal to your default value.
To set the input option at run time try setting the 'checked' value. (even if it isn't a checkbox)
elem.checked=true;
Where elem is a reference to the option to be selected.
So for the above issue:
var country = document.getElementById("country");
country.options[country.options.selectedIndex].checked=true;
This works for me, even when the options are not wrapped in a .
If all of the tags share the same name, they should uncheck when the new one is checked.
Realize this is an old question, but with the newer version of JQuery you can now do the following:
$("option[val=ID]").prop("selected",true);
This accomplishes the same thing as Box9's selected answer in one line.
The ideas on this page were helpful, yet as ever my scenario was different. So, in modal bootstrap / express node js / aws beanstalk, this worked for me:
var modal = $(this);
modal.find(".modal-body select#cJourney").val(vcJourney).attr("selected","selected");
Where my select ID = "cJourney" and the drop down value was stored in variable: vcJourney
I was trying something like this using the $(...).val() function, but the function did not exist. It turns out that you can manually set the value the same way you do it for an <input>:
// Set value to Indonesia ("ID"):
$('#country').value = 'ID'
...and it get's automatically updated in the select. Works on Firefox at least; you might want to try it out in the others.
To set value in JavaScript using set attribute , for selected option tag
var newvalue = 10;
var x = document.getElementById("optionid").selectedIndex;
document.getElementById("optionid")[x].setAttribute('value', newvalue);

Categories