Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add 'selected' on a option using 'setAttribute' with javascript

Tags:

javascript

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. :)

like image 754
Alberto Acuña Avatar asked Dec 10 '22 20:12

Alberto Acuña


1 Answers

Try 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>
like image 170
Oleksandr T. Avatar answered Jan 12 '23 01:01

Oleksandr T.