How To Set Select Option Value Dynamically in jQuery
This post will discuss setting the select option dynamically using jQuery. We’ll create a dropdown using HTML and add an option value dynamically using jQuery.The jQuery .val()
method will be used to add value options.
We’ll also let you know how to create a dropdown list dynamically using jQuery.
jQuery is a popular JavaScript library that has many inbuilt methods to modify DOM, It also simplifies the process of manipulating and updating select box options dynamically. I
jQuery option set selected
In this article, we’ll explore how to set select option values dynamically in jQuery. Using jQuery, we’ll create a country select box and select US as an option in the select element.
Create HTML Select Element
Let’s create a country name select box using html. A select box is defined using the element and contains multiple elements within it. Each element represents a choice that users can select. The sample select box example:
<select id="country"> <option value="IN">India</option> <option value="US">United States</option> <option value="NZ">New Zealand</option> </select>
Dynamicall Create Dropdown List using jQuery
We can also create a dropdown list dynamically using jQuery. Here, I’ll show you how to dynamically create a dropdown list based on an array of countries.
// define countries array var countries = [ { code: 'IN', name: 'India' }, { code: 'US', name: 'United States' }, { code: 'NZ', name: 'New Zealand' }, ]; // Function to populate the dropdown with dynamic options function populateDropdown() { var select = $('#country'); // Loop through the countries array and add options $.each(countries, function(index, country) { select.append($('<option>', { value: country.code, text: country.name })); }); } // Call the populateDropdown function to add dynamic options populateDropdown();
We have defined an array called countries, After that created a function called populateDropdown
to add options to the dropdown dynamically.
Setting Select Option Value Dynamically:
Now, We’ll select “US” value dynamically in HTML selection using the .val() method. This method allows you to change the selected option based on the condition.
var country = $('#country'); country.val('US');
Line 1: You need to select the element you want to manipulate. This can be achieved by targeting the element’s id.
Line 2: Let’s set the select box to choose “US” by providing its value ( ‘US’) as an argument to the .val()
method.
Dynamic Value Setting in jQuery
You can also set the select option value dynamically based on conditions in your JavaScript code.
var country = $('#country'); var newValue = 'NZ'; if(country_name == 'New Zealand") country.val(newValue);
Conclusion:
We have learned to select the element using jQuery and selector(like id). You can easily change the selected option based on your requirements using the .val()
method.
Originally published at https://www.js-tutorials.com on September 8, 2023.