最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin6浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 11

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>

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);

发布评论

评论列表(0)

  1. 暂无评论