Jump to content

How do you add options to a select box in JavaScript?


SubhanUllah

Recommended Posts

Add options to a select box in JavaScript:

1) Using the Option constructor and add() method:

First, use the Option constructor to create a new option with the specified option text and value:

let newOption = new Option('Option Text','Option Value'); 
Then, call the add() method of the HTMLSelectElement element:

const select = document.querySelector('select');  
select.add(newOption,undefined); 
2) Using the DOM methods

First, construct a new option using DOM methods:

// create option using DOM 
const newOption = document.createElement('option'); 
const optionText = document.createTextNode('Option Text'); 
// set option text 
newOption.appendChild(optionText); 
// and option value 
newOption.setAttribute('value','Option Value'); 
Second, add the new option to the select element using the appendChild() method:

const select = document.querySelector('select');  
select.appendChild(newOption); 

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...