简体   繁体   中英

Failing to populate the Options in Select element using javascript

The following code is able to generate the Select drop down list but it is not being populated with options. I am trying to create a 'day of the month' calendar. I am not sure where my code is wrong...

 var select_day = document.createElement('select');
 select_day.setAttribute('id', 'select_day');

 var dayArray = []; // populate day array
              for(var i=0; i <= 30; i++){
                    dayArray[i] = i + 1;
            }
 console.log(dayArray);

 // DATE - create and append options
 for(var i=0; i< dayArray.length; i++){
    var option = document.createElement('option');
    option.setAttribute('value', dayArray[i]);
    option.setAttribute('text', dayArray[i]);
    select_day.appendChild(option);
  }

The attribute that controls (in the absence of a child text node) the display text of an option is called label , not text .

 option.setAttribute('text', dayArray[i]); 

should be

option.setAttribute('label', dayArray[i]);

 var select_day = document.createElement('select'); select_day.setAttribute('id', 'select_day'); var dayArray = []; // populate day array for (var i = 0; i <= 30; i++) { dayArray[i] = i + 1; } console.log(dayArray); // DATE - create and append options for (var i = 0; i < dayArray.length; i++) { var option = document.createElement('option'); option.setAttribute('value', dayArray[i]); option.setAttribute('label', dayArray[i]); select_day.appendChild(option); } document.body.appendChild(select_day); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM