Set option "selected" from dynamically created option

I have a dynamically created select option using javascript function. object of choice

<select name="country" id="country"> </select> 

when the js function is executed, the country object

 <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 display Indonesia as the default option. note: this option does not have the selected="selected" attribute.

then I need to set the 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 see the option "Indonesia" is like this

 <option value="ID" selected="selected">Indonesia</option> 

but it does not work in IE (tested in IE 8).

and then I tried using jQuery

 $( function() { $("#country option:selected").attr("selected", "selected"); }); 

it does not work in both FFX and IE.

I need the Indonesia option to have the selected="selected" attribute, so when I click the reset button it will select Indonesia again.

changing the js function to dynamically create country parameters is not an option. The solution should work in both FFX and IE.

Thank you

+60
javascript jquery select attributes option
Jan 04 2018-11-11T00:
source share
16 answers
Good question. You will need to change the HTML itself, rather than relying on the 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 in a new div (not in the document) to retrieve the full HTML string: <option value="ID">Indonesia</option> .

He then replaces the string to add the selected="selected" attribute as a string before replacing the original version with this new one.

I tested it on IE7. See how the reset button works here: http://jsfiddle.net/XmW49/

+26
Jan 04 2018-11-11T00:
source share
β€” -

You think too much:

 var country = document.getElementById("country"); country.options[country.options.selectedIndex].selected = true; 
+104
Jan 04 '11 at 4:12
source share

Instead of modifying the HTML itself, you should simply set the desired value from the relative option element:

 $(function() { $("#country").val("ID"); }); 

In this case, "ID" is the value of the "Indonesia" option.

+23
Dec 04 '12 at 19:11
source share

So many wrong answers!

To specify the value that should be returned in the form field after the form is reset, use the following properties:

  • Check box or radio button: defaultChecked
  • Any other <input> defaultValue : defaultValue
  • Option in the drop-down list: defaultSelected

So, to indicate the currently selected default option:

 var country = document.getElementById("country"); country.options[country.selectedIndex].defaultSelected = true; 

It may be a good idea to set the defaultSelected value for each option, if previously set:

 var country = document.getElementById("country"); for (var i = 0; i < country.options.length; i++) { country.options[i].defaultSelected = i == country.selectedIndex; } 

Now that the form is reset, the selected option will be the one you specified.

+13
Nov 07 '15 at 2:29
source share
 // 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);​​ 
+11
Oct 24 '12 at 12:28
source share

What you want to do is set the selectedIndex attribute in the selection box.

 country.options.selectedIndex = index_of_indonesia; 

Changing the 'selected' attribute usually does not work in IE. If you really like the behavior that you describe, I suggest you write a custom javascript reset function to reset all other values ​​in the default form.

+9
Jan 04 '11 at 3:10
source share

It works in FF, IE9

 var x = document.getElementById("country").children[2]; x.setAttribute("selected", "selected"); 
+6
Feb 08 '13 at 6:11
source share
 // 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.

+2
Jan 4 '11 at 3:14
source share

You can search all parameter values ​​until you find the correct one.

 var defaultVal = "Country"; $("#select").find("option").each(function () { if ($(this).val() == defaultVal) { $(this).prop("selected", "selected"); } }); 
+1
May 03 '13 at 19:16
source share

That should work.

 $("#country [value='ID']").attr("selected","selected"); 

If you have function calls bound to an element, just follow it with something like

 $("#country").change(); 
+1
Feb 08 '14 at 17:23
source share
 select = document.getElementById('selectId'); var opt = document.createElement('option'); opt.value = 'value'; opt.innerHTML = 'name'; opt.selected = true; select.appendChild(opt); 
+1
Nov 29 '16 at 15:10
source share

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), HTMLFormElement.reset() - defaultSelected is used to set the Attribute- selected parameter and to survive it:

 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 create the parameters dynamically and then ( only after that ) you want to set one parameter to 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> 

Option gets Attribute selected by using defaultSelected

Make parameter defaultSelected when dynamically creating parameters

To make the selected parameter when filling in the SELECT element , use the Option() MDN constructor

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 elements from rendering inside the DOM in a loop. Instead, a fragment (containing all parameters) is added to the selection only once.




SELECT.value vs OPTION.setAttribute vs OPTION.selected vs OPTION.defaultSelected

Although some (older) browsers interpret the OPTION selected attribute as a "string" state, the WHATWG html.spec.whatwg.org HTML specifications state that it should represent a logical selectedness

Selecting an option element is a logical state , initially false. Unless otherwise specified, when creating an element, its selection must be set to true if the element has the selected attribute.
html.spec.whatwg.org - Option selectedness

It can be correctly concluded that only the selected name in <option value="foo" selected> enough to set the true state.




Comparative test of various 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 test 2. using .setAttribute() at first glance seems to be the best solution, since both the property of the element and the attribute are unison, it can lead to confusion , especially because .setAttribute expects two parameters:

 EL_select.options[1].setAttribute('selected', false); // <option value="AL" selected="false"> // But still selected! 

actually make the choice selected

Should I use .removeAttribute() or perhaps .setAttribute('selected', ???) for a different value? Or should you read the state using .getAttribute('selected') or .hasAttribute('selected') ?

Instead, test 3. (and 4.) using defaultSelected gives the expected results :

  • The selected attribute as the named selection state .
  • The selected property in an element object with a boolean value .
+1
Aug 07 '19 at 3:16
source share

To set the input parameter at run time, try setting the value to "checked". (even if it is not a check box)

 elem.checked=true; 

Where elem is the link to the selected option.

So, for the above problem:

 var country = document.getElementById("country"); country.options[country.options.selectedIndex].checked=true; 

This works for me, even if the options are not wrapped in.

If all tags have the same name, they should clear the check box if a new check box is selected.

0
Apr 03 '13 at 2:59
source share

Understand this is an old question, but with a newer version of jQuery you can do the following:

 $("option[val=ID]").prop("selected",true); 

Performs the same as Box9, on one line.

0
Apr 22 '14 at 21:09
source share

The ideas on this page were helpful, but my script was different. So in the js / aws beanstalk modal boot / express node this works 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 were stored in a variable: vcJourney

0
Jun 25 '18 at 10:32
source share

I tried to use something like this with the function $(...).val() , but there was no function. Turns out you can manually set the value the same way you do it for <input> :

 // Set value to Indonesia ("ID"): $('#country').value = 'ID' 

... and it automatically updates when selected. At least it works on Firefox; You can try it in others.

-one
May 27 '16 at 12:03
source share



All Articles