Javascript change select option values

Changing a select element option using JavaScript.

This is a short JavaScript tutorial on how to change the selected option of a select HTML element. In this post, I will show you how to do it with and without JQuery.

Changing a select option without JQuery.

In this example, I am going to use vanilla JavaScript. Although the JQuery library is great, you may find yourself in situations where you don’t have access to it. It’s also not a terrific idea to include an entire library just for the sake of changing a select element.

Take a look at the custom JavaScript function that I wrote:

//Custom function that changes a select element's option. function select(selectId, optionValToSelect) < //Get the select element by it's unique ID. var selectElement = document.getElementById(selectId); //Get the options. var selectOptions = selectElement.options; //Loop through these options using a for loop. for (var opt, j = 0; opt = selectOptions[j]; j++) < //If the option of value is equal to the option we want to select. if (opt.value == optionValToSelect) < //Select the option and break out of the for loop. selectElement.selectedIndex = j; break; >> >

The JavaScript function above takes in two parameters. The unique ID of our select element and the value that we want to select. Inside our function, we loop through each option in the select element. If the value of the option matches the value that we want to select, we change the selectedIndex of the element and break out of the for loop.

An example of this function being used with a dropdown containing a list of country names:

   

In the example above, I used our custom function to select Ireland.

Changing a select option using JQuery.

If you’re already using the JavaScript JQuery library, then you can do something like this:

//We want to select Ireland. var optionToSelect = 'Ireland'; //Change the #countries select element to the Ireland option. $('#countries option:contains(' + optionToSelect + ')').attr('selected', 'selected');

In the JQuery code above, we changed our select element option to “Ireland” using the attr method. However, you can also use the prop method:

var optionToSelect = 'Ireland'; $('#countries option:contains(' + optionToSelect + ')').prop();

In some cases, your value attributes might differ from the text of each option.

 

This is a common when you are dealing with select elements that were populated from a database or an array. In this scenario, you can use the following JQuery snippet:

//Ireland is 3 in our select element. var valueToSelect = 3; $('#countries').val(valueToSelect);

In the code above, we changed our select element by using the val method. We set it to 3 because the Ireland option in our list has a value attribute of 3.

Читайте также:  Java util list element

And that’s it! Hopefully, the above examples solved your problem!

Источник

Javascript change select option values

Last updated: Jan 11, 2023
Reading time · 3 min

banner

# Set the Value of a Select Element using JavaScript

Use the value property to set the value of a select element, e.g. select.value = ‘new value’ .

The value property can be used to set or update the value of a select element. To remove the selection, set the value to an empty string.

Here is the HTML for the examples.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> head> body style="margin-top: 60px; margin-left: 100px"> select name="fruits" id="fruit-select"> option value="">--Choose an option--option> option value="apple">Appleoption> option value="banana">Bananaoption> option value="kiwi">Kiwioption> select> button style="margin-top: 10px" id="btn">Clickbutton> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
const select = document.getElementById('fruit-select'); // ✅ set select value select.value = 'apple'; console.log(select.value); // 👉️ "apple" // ✅ unset select value // select.value = ''; // -------------------------------- const allOptions = Array.from(select.options).map(option => option.value); console.log(allOptions); // 👉️ ['', 'apple', 'banana', 'kiwi'] // -------------------------------- // ✅ get select value on change select.addEventListener('change', function handleChange(event) console.log(event.target.value); // 👉️ get selected VALUE >); // -------------------------------- // ✅ Set select element value on button click const btn = document.getElementById('btn'); btn.addEventListener('click', function handleClick() select.value = 'banana'; >);

We used the value property to set the value of a select element.

A convention for when you don’t have a default value is to have the value of the first option element be an empty string.

# Removing the selection

To remove the selection, set the value property of the select element to an empty string.

Copied!
const select = document.getElementById('fruit-select'); // ✅ set select value select.value = 'apple'; console.log(select.value); // 👉️ "apple" // ✅ unset select value select.value = '';

# Getting an array of the values of all option elements

If you need an array of the values of all the option elements, use the map() method to iterate over the elements and return the value of each option .

Copied!
const select = document.getElementById('fruit-select'); // ✅ set select value select.value = 'apple'; console.log(select.value); // 👉️ "apple" const allOptions = Array.from(select.options).map(option => option.value); console.log(allOptions); // 👉️ ['', 'apple', 'banana', 'kiwi']

# Changing the value of a select element

The value of a select element can be changed in the same way it is set, just update the value property.

Copied!
const select = document.getElementById('fruit-select'); select.value = 'apple'; console.log(select.value); // 👉️ "apple" select.value = 'banana'; console.log(select.value); // 👉️ "banana"

If you set a select element’s value to a value that is not present among the option elements, the value of the select element gets reset.

Copied!
const select = document.getElementById('fruit-select'); select.value = 'does-not-exist'; console.log(select.value); // 👉️ ""

You can create an object that stores the values of the option elements to avoid misspelling values.

Copied!
const select = document.getElementById('fruit-select'); const values = apple: 'apple', banana: 'banana', kiwi: 'kiwi', >; select.value = values.apple; console.log(select.value); // 👉️ "apple" select.value = values.banana; console.log(select.value); // 👉️ "banana"

This is a much better solution than hard-coding strings all over the place because it leverages your IDE’s autocompletion.

It also helps the readers of your code know what the alternative values of the select element are.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Manipulation of HTML Select Element with Javascript

Manipulation of the element with Javascript is quite commonly required in web applications. This tutorial explains how you can perform common operations on select element with vanilla Javascript — adding/deleting options or getting/setting the selected options.

Important Properties and Methods of Select Element

  • value : It gives the value of the first selected option (a multi-valued select may have multiple selected options)
  • options : It gives the list of all option elements in the select
  • selectedOptions : It gives the list of option elements that are currently selected
  • selectedIndex : It is an integer that gives the index of first selected option. In case no option is selected, it gives -1
  • add() : This method adds a new option to the list of options
  • remove() : This method removes an option from the select element

Important Properties of Option Element

  • value : It gives the value of the option
  • text : It gives the text inside the option
  • selected : It tells whether the option is selected or not

Setting Value of Select Element

For a single valued select, setting its value can be done with the value or the selectedIndex property.

// Set option with value 'Orange' as selected document.querySelector('#choose-fruit').value = 'Orange'; // Set the option with index 2 as selected => Sets the 'Banana' option as selected document.querySelector('#choose-fruit').selectedIndex = 2; 

For a multiple valued select, setting multiple selected options can be done by setting the selected attribute of the required option.

  
// choose the first option document.querySelector('#choose-fruit-multiple').options[0].selected = true; // also choose the third option document.querySelector('#choose-fruit-multiple').options[2].selected = true; 

This will obviously work for single valued select also, but using the value property is much direct for them.

Getting the Value and Text/Label of the Selected Options

The selectedOptions property of the select element gives the list of options that are currently selected. Each element in this list is a DOM element — so you can use the value and text property to get the value and inside text of the option.

// For a normal select (and not multi-select) the list would contain only a single element var text = document.querySelector('#choose-fruit').selectedOptions[0].text; var value = document.querySelector('#choose-fruit').selectedOptions[0].value; 

For a multiple select element, you can loop over the list to get all selected options.

  
var selected_options = document.querySelector('#choose-fruit-multiple').selectedOptions; for(var i=0; i // output Orange 2 Grapes 5 

Adding an Option

The add method can be used to add a new option in the select. You can also specify the exact positon where the option needs to be inserted.

var option = document.createElement('option'); option.text = 'BMW'; // append option at the end // new options will be Volvo, Audi, Mercedes & BMW document.querySelector('#choose-car').add(option, null); 
var option = document.createElement('option'); option.text = 'BMW'; // append option before index 0 // new options will be BMW, Volvo, Audi & Mercedes document.querySelector('#choose-car').add(option, 0); 
var option = document.createElement('option'); option.text = 'BMW'; // append option before index 2 // new options will be Volvo, Audi, BMW & Mercedes document.querySelector('#choose-car').add(option, 2); 

Deleting an Option

The remove method can be used to delete an option at a specified index.

// remove the option at index 1 // new options will be Volvo & Mercedes document.querySelector('#choose-car').remove(1); 

Источник

Оцените статью