Fro example, I have this, and im trying to set by default option1, will be selected for default, how i can do it only using OPT.setAttribute(...,..):
var SELECT = document.createElement('SELECT');
var OPT1 = document.createElement('OPTION');
OPT1.setAttribute('value', 0);
var OPT2 = document.createElement('OPTION');
OPT2.setAttribute('value', 0);
OPT1.appendChild( document.createTextNode( 'option1' ) );
OPT2.appendChild( document.createTextNode( 'option2' ) );
SELECT.appendChild(OPT1);
SELECT.appendChild(OPT2);
Im trying this :
OPT1.setAttribute('selected','true');
Obviusly dont work, thanks for help. :)
Fro example, I have this, and im trying to set by default option1, will be selected for default, how i can do it only using OPT.setAttribute(...,..):
var SELECT = document.createElement('SELECT');
var OPT1 = document.createElement('OPTION');
OPT1.setAttribute('value', 0);
var OPT2 = document.createElement('OPTION');
OPT2.setAttribute('value', 0);
OPT1.appendChild( document.createTextNode( 'option1' ) );
OPT2.appendChild( document.createTextNode( 'option2' ) );
SELECT.appendChild(OPT1);
SELECT.appendChild(OPT2);
Im trying this :
OPT1.setAttribute('selected','true');
Obviusly dont work, thanks for help. :)
Share Improve this question asked Nov 12, 2015 at 9:54 Alberto AcuñaAlberto Acuña 5353 gold badges10 silver badges30 bronze badges2 Answers
Reset to default 11Try this
var SELECT = document.createElement('SELECT');
var OPT1 = document.createElement('OPTION');
OPT1.setAttribute('value', 0);
var OPT2 = document.createElement('OPTION');
OPT2.setAttribute('value', 0);
OPT2.setAttribute('selected', 'selected');
// also you can set use .selected as a property
// OPT2.selected = true;
OPT1.appendChild( document.createTextNode( 'option1' ) );
OPT2.appendChild( document.createTextNode( 'option2' ) );
SELECT.appendChild(OPT1);
SELECT.appendChild(OPT2);
document.getElementById('select').appendChild(SELECT);
<div id="select"></div>
Either you need to do OPT1.setAttribute('selected','selected');
before SELECT.appendChild(OPT1);
or you need to do SELECT.selectedIndex = Array.prototype.indexOf.call( SELECT.children, OTP1);