Guide on setting the dropdown's selected index through JavaScript

Is there a way to use javascript to set the selected value of a dropdown?

Here is the HTML code I am working with:

<select id="strPlan" name="strPlan" class="formInput">
    <option value="0">Select a Plan</option>
</select>

I am trying to dynamically add values using javascript. Can anyone provide guidance on how to call a function to select a specific value?

Answer №1

How can I set the selected value of a dropdown using javascript?

If you are looking to change the value of the currently selected option in a dropdown, you can achieve that with the following JavaScript code:

function setSelectedValue(selectElement, valueToSet){
    selectElement.options[selectElement.selectedIndex].value = valueToSet;
}

To use this function, simply call it like this:

setSelectedValue(document.getElementById('strPlan'), 'selected');

For a live demonstration, you can check out this Demo


If you are looking to select an option in the dropdown based on its value, you can use the following function:

Define this function in your JavaScript:

function selectOptionByValue(selectElement, value){
    var options = selectElement.options;
    for(var i = 0; i < options.length; i++){
        if(options[i].value === value){
            selectElement.selectedIndex = i;
            return true;
        }
    }
    return false;
}

To set the option by its value, use the function like this:

selectOptionByValue(document.getElementById('strPlan'), '1');

For a demonstration, you can visit this Demo

Answer №2

This method seems promising to me:

function updateDropDownSelection(element, newValue)
{
    let foundValue = false;

    for (let i = 0; i < element.options.length; i++) {
        if (element.options[i].value == newValue) {
            element.options[i].selected = true;
            foundValue = true;
        }
    }

    if (!foundValue)
        element.options[0].selected = true;
}

I came across this solution here. Try searching for 'set selected value dropdown javascript' on Google for more options.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to continuously refresh the display in AngularJS

There are 2 div elements below, and I need to display only one of them depending on whether the doStuff() function is triggered in the controller when a specific anchor element is clicked. <div ng-controller='myController'> <div ng- ...

Replace all occurrences of $regex in Node.js with the json data format

Here is a JSON example var json= { name: { '$regex': /^Amer$/i }, 'countries.name': { '$regex': /^UNited states$/i } } I am looking to reformat it using either lodash or string/json replace method to achieve the following st ...

Generate several sliders using JQuery effortlessly

As I was attempting to create multiple sliders with JQuery in a more automated fashion using iteration, several questions arose (you can see a functional example below). Why does the first block of JQuery code work while the second block of JavaScript cod ...

Switching from PHP to jQuery or JavaScript can make for a

I've been attempting to convert this PHP code to jQuery or JavaScript without success. I'm still learning about jQuery and JavaScript Check out the original PHP code: <?php // Set timezone date_default_timezone_set('UTC'); ...

What is the difference between using || (or) and defining a variable in JavaScript?

Similar Inquiry: What is the meaning of the expression (x = x || y)? On numerous occasions, I have noticed variables being assigned in this manner var d = d || {} or var = var || [] This has raised a few questions in my mind What is the main pu ...

What causes certain webpack / Babel ES6 imports without a specified extension to resolve as "undefined"?

When I try to import certain ES6 files (such as .js, .jsx, .ts, .tsx) using the syntax import ComponentName from './folder/ComponentName'; (without extension), they end up resolving as undefined. This occurs even though there are no errors from W ...

Controller experiencing issues with Ajax passing null value

My webpage features a dropdown menu with a list of ID's to choose from. When a customer selects an option, it should update the price total displayed on the page. To achieve this functionality, I'm working on implementing an AJAX call that will u ...

Update the JSON by replacing any null values with a predefined string

When working with JSON data, I often come across empty values that I need to replace with a default string. var jsonData= [ { "machineNum": "1A", "serialNo": "123", "city": "" }, { "machineNum": "2B", "serialNo": "", "city": "" }, ...

What is the best way to dynamically adjust the size of a grid of divs to perfectly fit within the boundaries of a container div without surpassing them?

Currently, I am working on a project for "The Odin Project" that involves creating a web page similar to an etch-a-sketch. I have made some progress, but I am facing a challenge with dynamically resizing a grid of divs. The issue lies with the container d ...

The AJAX success function is operational, yet the file does not execute

As a newcomer to StackOverflow and web development, I am pressed for time with this assignment, so please bear with me if I struggle with understanding web development terminologies. My current challenge involves calling another php file through ajax in my ...

Change the controller's classes and update the view in Angular

In my angular application, I have a popup window containing several tabs. These tabs are styled like Bootstrap and need to be switched using Angular. The code for the tabs is as follows (simplified): <div class="settingsPopupWindow"> <div> ...

Why does the Element.style.left property keep rejecting my input value?

I have encountered a problem with the positioning of elements, specifically with the 'left' property. I've designed a rectangular block using CSS and rotated it by 0.17 radians in JavaScript. Now, my aim is to make the block move diagonally ...

When utilizing Google Analytics in conjunction with Next.Js, encountering the error message "window.gtag is not

Encountering an error on page load with the message: window.gtag is not a function Using Next.js version 14.0.4. All existing solutions seem to hinder data collection, preventing the website from setting cookie consent correctly. I am uncertain about the ...

Floating dropdown within a scrolling box

How can I ensure that the absolute positioned dropdown remains on top of the scrollable container and moves along with its relative parent when scrolling? Currently, the dropdown is displayed within the scrollable area. The desired layout is illustrated i ...

Sending a C# variable to an HTML file

I’m struggling to understand how I can use jQuery to access a variable from C# named sqlReq. My main objective is to be able to input my own SQL data into a PieChart. However, I’m unsure about how to call and define C# SQL requests in HTML or jQuery. ...

Steps to create a pop-up displaying a unique message ID retrieved from my database

My goal is to implement a pop-up message dialog on my website. When a user clicks on a reply icon, a pop-up message will appear with a textarea for the user to respond to a question they have been asked. The current issue is that clicking on the tag alway ...

Discover the best way to retrieve XML information from various sources specifically designed for Windows gadgets using JavaScript

I have previously visited this site and have not been able to locate a solution that I believe will be suitable for my Windows 7 desktop gadget. In essence, I am seeking a method to retrieve XML data from weather.gov using Javascript (or any other means t ...

Activating Ionic6 Stack Modal through JavaScript or TypeScript

Is it possible to trigger the modal using script code instead of a button? I have searched through various examples in the tutorial, but all of them rely on the modal trigger mechanism. <ion-button id="open-modal" expand="block">O ...

New to NodeJS: Utilizing Requestify to Retrieve Data from Another URL

As a newcomer in the world of NodeJs, I am faced with the task of transitioning my CodeIgniter server APIs to Node.js. Currently, I am utilizing requestify to retrieve data from a web service, and once this is accomplished, I intend to invoke an insert met ...

Show a success message once the jQuery Ajax operation is successful and then refresh the page

I am looking to implement a feature where a Bootstrap alert message is shown immediately following a successful AJAX request and page refresh. success: function(res) { window.location.reload(); $('#success').html('<div class=&qu ...