Steps to remove a chosen option from a dropdown list if the user decides not to proceed with the selection

I am currently working with this JavaScript code:

function change(selection){
    if(confirm("Select this option?"))
    {

    } else {
        if(selection=="1")
        {
            alert("Return selected to NO");
        } else {
            alert("Return selected to YES");
        }
    }

}

Here is the corresponding HTML code snippet:

<select id="sel" name="sel" onchange="change(this.value)">
    <option value="1">YES</option>
    <option value="0">NO</option>
</select>

My Desired Outcome:

Assume that by default, the selected option is YES. If the user chooses to select NO, confirmation boxes will appear asking if they want to switch to NO or not. If they click "OK", then the NO option will be selected. However, if they click "CANCEL", no selection will be made and the YES option stays selected. The same process applies vice versa.

To see a live example, check out this Fiddle: http://jsfiddle.net/CtxUy/

Answer №1

In case you are focused only on these specific elements, simply assign the values manually:

if(varam=="1")
{
    document.getElementById('sel').value = 0;
} else {
    document.getElementById('sel').value = 1;
}

If there could be additional values involved, one approach is to keep track of the initially selected value and revert the selector value to that when a confirmation is declined, or update that stored value if they confirm.

Example: http://jsfiddle.net/CtxUy/2/

Answer №2

To determine which option is selected, you can loop through the options and choose the one with the selected attribute. If none have this attribute, simply select the first option by default.

var select = document.getElementById('sel');
var options = select.options;
options[0].selected = true; // Select the first option as a backup

for (var i = 0, l = options.length; i < l; i++) {
    if (options[i].hasAttribute('selected')) {
        options[i].selected = true;
        break;
    }
}

Check out the DEMO here!

For more info: HTMLSelectElement, HTMLOptionElement.

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

How can I generate 200 divs that are identical but each displaying a unique file (page0.svg, page1.svg..., page200.svg)?

<div class="mySlides"> <img src="1173/page0.svg" style="width:50%"> </div> <div class="mySlides"> <img src="1173/page1.svg" style="width:50%"> </div> My task involves generating approximately 200 similar div codes ...

The callback in Jquery getJSON does not execute even when a valid JSON response is received

My server is sending valid JSON objects (as verified by jsonlint.com) that have this structure: "{\"encryption\": {\"key\": \"gKV0oPJwC5CBQxmn\"}}" This is how my HTML file looks: <html> <head> <title&g ...

Using HTML code within a Bootstrap 5 tooltip is a great way

After referring to the official documentation, I am trying to show some HTML content inside a bootstrap 5 tooltip. Unfortunately, simply copying and pasting code from the documentation does not produce the desired result. <button type="button" ...

Acquire the <li> element when it is clicked using vanilla JavaScript

Whenever a user enters a value in an input field, my function automatically adds a <li> element to a <ul>. Additionally, the function assigns the attribute ( onclick="doneToggle" ) to the created <li>. function createListElement() { ...

Utilizing the power of jQuery's `.clone` method to create a new window with fully

I am currently working on a project where I need to duplicate a page while maintaining its functionality, and then display it in a new window. My goal is to only clone a specific portion of the page, but for now I am focusing on replicating the entire page ...

Creating prototypes for objects starting from an empty state

Below is the custom code structure I have created: module.exports = (function() { Function.prototype.extend = function(obj) { for (var prop in obj) { this[prop] = obj[prop]; } } })(); var CustomHelpers = {}; CustomHelpers.prototype.get ...

Angular allows for displaying objects within other objects using interpolation

Below is the object stored in EntryList variable within my component: { "id": 0, "startAddress": { "id": 6, "addressString": "addressString" }, "endAddress": { ...

Sort Angular JS ng-options based on an array

Is there a way to filter ng-options with an array? For example: <select ng-model="currentItem.Community.white_label_id" ng-options="whitelabel.WhiteLabel.id as whitelabel.WhiteLabel.name for whitelabel in whitelabels | filter:whitelabel.WhiteLa ...

The canvas game's animation can only be activated one time

I am currently working on designing a straightforward canvas game: Here is the code snippet located on CodePen var canvas; var ctx; var x = 300; var y = 400; var r = 0; var mx = 0; var my = 0; var WIDTH = 600; var HEIGHT = 400; function circle(x,y,r) ...

Encountering the error "Vue 2.0 encounters an undefined push during router.push

I'm currently working on a project that involves implementing a function to route the list of subMenus displayed by the mainMenu. Each subMenu is identified by its specific name, which I would like to append and use as the route path that I am aiming ...

Constructing variable names in AngularJS while using ng-repeat

I am working with a series of items that are structured as described below. Unfortunately, I do not have control over the variable names. pubDate0, pubDate1, pubDate2 To access them, I currently use the following format: <div> <i> ...

How far apart are two surfaces when they are rotated along the Y-axis

Access Code: Click here to access the code I am trying to make sure that the red surface lies completely flat on top of the gray surface. However, there seems to be a gap (marked ??) between the two surfaces when I rotate 'modifier1'. How can I ...

JavaScript application throwing error: "require is not defined"

Currently, I am working on storing an array in a .json file using NodeJS. However, when trying to execute the code below, I encountered an error message saying require is not defined. Can someone provide some guidance on how to resolve this issue? let ans ...

Utilizing React with an alternative server-side language

I have a small PHP backend for my website and I want to incorporate React on the front end. However, being new to front-end development and React, I am finding this process confusing as most online examples assume a JavaScript backend with Node modules. W ...

What is the best way to validate email addresses in Vue.js using watchers?

watch: { email(value) { this.email = value; this.validateEmail(value); }, }, methods() { validateEmail() { // eslint-disable-next-line if (/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<> ...

vue mapGetters not fetching data synchronously

Utilizing vuex for state management in my application, I am implementing one-way binding with my form. <script> import { mapGetters } from 'vuex' import store from 'vuex-store' import DataWidget from '../../../../uiCo ...

The function called Nuxt: n2 is not defined

When using Nuxt 3, I encountered a TypeError that looks like the following: Uncaught TypeError: n2 is not a function My issue revolves around a button that triggers the function toggleSelectRow with a @click.prevent directive. The function in question is ...

How can I access the value of a textbox located in the footer row of a gridview control using JavaScript?

Below is the code snippet for a gridview in an aspx page, where the gridview is placed inside a form tag. <Grdview:GridViewExtended ID="GridView1" runat="server" AutoGenerateColumns="False" CssClass="Grid" onpageindexchanging="GridView1_Pa ...

After a two-second period of inactivity, the buttons on the item should trigger an action

I have a scenario in mind that I want to implement: When the user clicks on either the "Plus" or "Minus" button. If the user doesn't click on any of those buttons within 2 seconds, then we assume that the current quantity should be sent to the server ...

Utilize environment variables to access system information when constructing an Angular 2 application

In order to build my Angular application, I want to utilize a single system variable. System Variable server_url = http://google.com This is how my Environment.ts file looks: export const environment = { production: false, serveUrl: 'http://so ...