Refresh a selection menu using a checkmark

Can you help me with a script to enable/disable a dropdown based on the checkbox status?

    <body onload="enableDropdown(false);">

<form name="form1" method="post" onload="enableDropdown(false);">
<input type="checkbox" name="others" onclick="enableDropdown(this.checked)" >Others

    <select id="selected_opt">
  <option value="x">X</option>
  <option value="y" selected>Y</option>
  <option value="z">Z</option>
</select></form>

Here is the Javascript code:

function enableDropdown(bool)
{
bool = !bool; 
document.form1.selected_opt.disabled = bool;
}

Answer №1

When you mention "reset the dropdown", are you referring to re-selecting the initial value?

An easy solution is to include the following in your JavaScript code:

document.form1.dropdownName.value = "b";

A more sophisticated approach would be:

<form name="form1" method="post" onload="disableDropdown(false);">
    <input type="checkbox" name="otherOptions" onclick="disableDropdown(this.checked)" >Other Options

    <select id="dropdownName">
        <option value="x">X</option>
        <option value="b" selected data-default="true">B</option>
        <option value="y">Y</option>
    </select>
</form>

JavaScript function:

function disableDropdown(status)
{
    var dropdown = document.form1.dropdownName;

    status = !status;
    dropdown.disabled = status;

    for (var j = 0; j < dropdown.children.length; ++j) {
        if (dropdown.children[j].dataset.default === "true") {
            dropdown.value = dropdown.children[j].value;
            break;
        }
    }
}

Answer №2

Give this a try:

function toggleDropdown(inputStatus)
{
  var dropdown = document.getElementById("my_dropdown");

  if(inputStatus == true)
  {
       // $(dropdown).removeAttr("disabled");
       dropdown.removeAttribute("disabled");
  }
  else
  {
        // $(dropdown).attr('disabled', 'disabled');
      dropdown.setAttribute("disabled","disabled");
  }

      // Reset the selected index of the dropdown to clear current selection
      dropdown.selectedIndex = -1;
}

Answer №3

Discover how to implement this code snippet with jQuery

HTML

<form name="f1">
   <input type="checkbox" name="others" id="chk" > Others
   <select id="that_select" disabled>
     <option value="a">A</option>
     <option value="b" selected>B</option>
     <option value="c">C</option>
   </select>
</form>

jQuery

$('#chk').change(function(){ 
    if($('#chk').is(':checked')){
        $('#that_select').removeAttr('disabled');
    }
    else{
        $('#that_select').attr('disabled','disabled');
    }
});

JSFIDDLE DEMO

Answer №4

function toggle_dropdown(disable) {
  var disable = !disable;
  if (disable) {
    document.form.selected.setAttribute("disabled", disable);

  } else {
    document.form.selected.removeAttribute("disabled");
  }

}
<body onload="toggle_dropdown(false)">

  <form name="form" method="post">
    <input type="checkbox" name="others" onclick="toggle_dropdown(this.checked)">Others
    <select id="selected" name="selected">
      <option value="a">A</option>
      <option value="b" selected>B</option>
      <option value="c">C</option>
    </select>
  </form>

</body>

Hopefully, this code snippet is helpful.

Answer №5

Here is the code snippet you requested:

 <body onload="enable_dropdown(false);">
<form name="f1" method="post" onload="enable_dropdown(false);">

Other Content

<select id="that_select">
    <option value="a">A</option>
    <option value="b" selected>B</option>
    <option value="c">C</option>
</select></form>


function enable_dropdown(status)
{
   var sel=document.getElementById('that_select');
       if(status||false) 
           sel.removeAttribute('disabled');
       else 
           sel.setAttribute('disabled','disabled');
}

Answer №6

Learning how to use JQuery can make your coding experience much smoother, check out this demo http://jsfiddle.net/spskqLwL/

<form name="f1" method="post">
<input type="checkbox" name="others">Others

<select id="that_select">
    <option value="a">A</option>
    <option value="b" selected>B</option>
    <option value="c">C</option>
</select></form>

Here's the jQuery code snippet:

$(function(){
    $("#that_select").prop('disabled',false);

    $("[type='checkbox']").change(function(){
        if($(this).is(":checked")) {
            $("#that_select").prop('disabled',true);
        }
        else{
            $("#that_select").prop('disabled',false);
        }
    });
});

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

Update the image and heading simultaneously when hovering over the parent div

I am looking to enhance the user experience on my website by changing the color of headings and images when a user hovers over a specific section. Currently, I have been able to achieve this effect individually for each element but not simultaneously. Any ...

What is causing my background image to move upward when I include this JavaScript code for FlashGallery?

There's an issue on my website where adding a flash gallery script is causing the background image to shift unexpectedly. You can view the affected page here: The culprit seems to be the "swfobject.js" script. I've identified this by toggling t ...

Guidelines for submitting and displaying content on a single page with jQuery and MySQL

Objective: To develop a Q&A Script using PHP, JavaScript, and jQuery that allows users to post questions and provide answers. Upon submitting a new answer, it should be stored in the database and automatically displayed in the answers section. Challenge: ...

Angular js: Understanding the use of "this" within the ng-if function

Is there anyone who can assist me with the following question: How do I access the "this" element within the ng-if (in my example, the classname is "class_to_obtain" of the span element)? http://plnkr.co/edit/0s7PCWN2fJ8sJpFSJssV HTML ...

Reactjs: When components are reused, conflicts may arise in UI changes

I'm currently working on creating a sample chat room application using reactjs and redux for educational purposes. In this scenario, there will be 3 users and the Message_01 component will be reused 3 times. Below is the code snippet: const Main = Re ...

Loading jQuery on an ajax request

The loader is working with the code now, but it is not replacing and calling the URL. The ajax url call should be placed within searchable. <button onclick="myFunction()">LOAD</button><br /><br /> <div class="spinner bar hide" ...

how to protect your javascript and php code

I have a question about "injection", specifically javascript injection which I find confusing. Suppose I have a javascript function that sends an AJAX request to get a user's permission level, and then uses an if statement to assign power based on th ...

The method of utilizing React with Redux to display component properties

I am currently trying to include my common component in my main.js file Successfully implemented this However, when attempting to print my Redux data values in the common component, I created a method called handleClickForRedux to handle this task. Even af ...

issue with manipulating URLs in Express routing

Looking for assistance with Express routing. I want users to only see localhost:3000/page2 when they go to /page2, instead of localhost:3000/page2.html I have three HTML pages - page1.html, page2.html, and page3.html. I've created a server using Expr ...

Tips on causing a forEach loop to pause for a regex substitution to occur

I have a project in progress for an email web app where I am working on replacing certain keywords (first name, last name, email) with the actual properties of the user. As of now, I am going through a list of recipients and modifying the email content to ...

What did I overlook in my AJAX implementation?

When a user selects a value from the dropdown menu, an Ajax call must be made to the server to retrieve some values in JSON format. Below is the Ajax code //AJAX Security $('#ddlSecurityLevel').change(function () { if ($('#ddlSecurityL ...

MongoSearch: A Geo-Targeted Search Engine tailored to your needs

For my new app project, I am using MongoDB, Express, JS, and Node to create a platform similar to Yelp. After some research, I discovered how to search for multiple fields within a campus schema (including campuses, restaurants, barbershops, and names). No ...

Mongoose managing diverse connections

Currently, I am working with Node.Js 8.6 and Mongoose 4.11, managing multiple database connections using mongoose.createConnection. Upon exploring the connections property within the mongoose object (an array that stores established connections), I am curi ...

Detach attention from TextField select component in Material UI and React through manual means

When I create a select input using the TextField component from Material-UI library, I need to manually remove focus after an option is selected. I attempted to achieve this by using a reference to the TextField with the 'inputRef' prop. However, ...

Utilizing Regular Expressions in AngularJS to validate name, a 10-digit mobile number, and a 12-digit number through the ng-blur event and match

I am struggling to validate the three inputs mentioned above and having trouble using the right functions. Can someone please assist me with this? Here is the HTML code for the 3 inputs: <input id="name" ng-model="user.name" ng-blur="checkIfNameIsVali ...

The variable X has been defined, but it's never actually utilized. Despite declaring it, I have not accessed its

I have encountered warnings in VSCode while using certain properties in my Angular component. The warnings state: '_id' is declared but its value is never read.ts(6133) (property) ItemEditComponent._id: number | undefined '_isModeEdit' ...

What is the best way to change the background color for my photo gallery?

I'm currently working on a project to create a unique photo gallery where each image has a different colored background. I have six images in total, but right now all of them have a pink background. I've attempted adding another .popup class in t ...

Transform a group of objects in Typescript into a new object with a modified structure

Struggling to figure out how to modify the return value of reduce without resorting to clunky type assertions. Take this snippet for example: const list: Array<Record<string, string | number>> = [ { resourceName: "a", usage: ...

Unexplainable space or padding issue detected in OwlCarousel grid gallery

There seems to be an unusual gap or margin at the bottom of each row section in this portfolio grid gallery that's running in OwlCarousel. You can view an example here. https://i.stack.imgur.com/NHOBd.png I've spent a lot of time trying to solv ...

FirebaseError encountered: Unable to update document due to absence of document. Updating document is only possible if document id is hard coded

For my latest project, I have a component that can successfully create a new user and add them to the database using the function createUserWithEmailAndPassword(auth, email, password). Now, I am working on another component that will allow users to edit t ...