Deactivate the selection option for the radio button that is checked in a specific

I am attempting to deactivate the selection when any of the "color1, color2, or color3" buttons are chosen. I desire it to be activated only when the "color4" radio button is selected. After consulting various sources, integrating it into my code has left me confused.

Below is my HTML:


        <br> <input type="radio" id="color1" name="color" value="orange" onchange="display()"  />
        <br> <input type="radio" id="color2" name="color" value="white" onchange="display()"  />
        <br> <input type="radio" id="color3" name="color" value="red" onchange="display()"  />

        // When checked, the select must be enabled
        <br> <input type="radio" id="color4" name="color" value="other" onchange="display()"  />
        <select id="other_color" onchange="display()" />
            <option value="black">black</option>
            <option value="pink">pink</option>
            <option value="green">Green</option> 
        </select>
        <div id="color_display" height="100px" width="100px"></div>
    

Now for my JavaScript:


        function display(){
            if(document.getElementById('color1').checked){
                document.getElementById('color_display').innerHTML = " Orange"; 
            } 
            if(document.getElementById('color2').checked){
                document.getElementById('color_display').innerHTML = " White"; 
            }
            if(document.getElementById('color3').checked){
                document.getElementById('color_display').innerHTML = " Red"; 
            }

            if (document.getElementById('other_color').value == 'black') {
                document.getElementById('color_display').innerHTML = " Black"; 
            }

            if (document.getElementById('other_color').value == 'pink') {
                document.getElementById('color_display').innerHTML = " Pink"; 
            }

            if (document.getElementById('other_color').value == 'green') {
                document.getElementById('color_display').innerHTML = " Green";
            }
        }
    

I have excluded the "color4" since it does not display anything. I intend for it to activate the selection. Do you think I should modify the existing JS or create a new one for this? I am unsure where to begin.

Answer №1

Based on my understanding, you can implement the following modifications in your JavaScript code.

document.getElementById("other_color").disabled = true; // Initially disable the select tag;

function display() {
  if (document.getElementById('color1').checked) {
    document.getElementById('color_display').innerHTML = " Orange";
  }
  if (document.getElementById('color2').checked) {
    document.getElementById('color_display').innerHTML = " White";
  }
  if (document.getElementById('color3').checked) {
    document.getElementById('color_display').innerHTML = " Red";
  }

  if (document.getElementById('color4').checked) {
    document.getElementById('other_color').disabled = false; // Enable the select tag when the fourth radio button is checked

    if (document.getElementById('other_color').value == 'black') {
      document.getElementById('color_display').innerHTML = " Black";
    }

    if (document.getElementById('other_color').value == 'pink') {
      document.getElementById('color_display').innerHTML = " Pink";
    }

    if (document.getElementById('other_color').value == 'green') {
      document.getElementById('color_display').innerHTML = " Green";
    }
  }
}

Answer №2

Make the adjustment to your JavaScript code as shown below:

function updateColorSelection() {
        if (document.getElementById('color4').checked) {
            document.getElementById("other_color").disabled = true;
        }
        else{
            document.getElementById("other_color").disabled = false;
        }
}

Answer №3

It seems like you are aiming to enhance the user experience by only displaying the select option when the "color4" radio button is selected, based on your initial post and subsequent comments. Below is a snippet that replicates this functionality:

Instead of initially showing the select option, it remains hidden until the user selects the "color4" radio button for a better user experience.

var color = document.querySelectorAll('input[name="color"]'),
    displaySelectedColour = document.getElementById("color_display"),
    selectOption = document.getElementById("other_color");
  
for (var i in color) {
    color[i].onclick = function() {
        if (document.getElementById('color1').checked == true) {
            displaySelectedColour.style.display = "block";
            displaySelectedColour.innerText = "Orange";
            selectOption.style.display = "none";
        }
        if (document.getElementById('color2').checked == true) {
            displaySelectedColour.style.display = "block";
            displaySelectedColour.innerText = "White";
            selectOption.style.display = "none";
        }
        if (document.getElementById('color3').checked == true) {
            displaySelectedColour.style.display = "block";
            displaySelectedColour.innerText = "Red";
            selectOption.style.display = "none";
        }
        if (document.getElementById('color4').checked == true) {
            displaySelectedColour.style.display = "none";
            selectOption.style.display = "block";
        }
    };
}
<input type="radio" id="color1" name="color" value="orange">
<br><input type="radio" id="color2" name="color" value="white">
<br><input type="radio" id="color3" name="color" value="red">
<br><input type="radio" id="color4" name="color" value="other">

<!-- Select disabled by default and enabled only on color4 radio button check -->
    <br>
    <select id="other_color" style="display: none;">
    <option disabled selected value>-- Select one --</option>
             <option>black</option>
             <option>pink</option>
             <option>green</option>
    </select>
    <div id="color_display" height="100px" width="100px"></div>

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

Is there a way to trigger a function in an AngularJS controller from a Backbone controller?

I've been working on an application that was originally developed using backbone and jQuery, but we had to incorporate new modules built with angular to meet client requirements. Routing in the application is handled by backbone route, and we have suc ...

Upon selecting the display image option

Here is a jsfiddle file provided for your reference. I am attempting to create a functionality where upon clicking buttons (1,2,3,4), the corresponding image shows up and overlaps with any previously displayed images. I have tried using the following code ...

How can you call a function in ExpressJS that is located in a different file?

I am having trouble with my UserController and database configuration file db.js. I am trying to make a function in the UserController access a function in db.js. In my UserController, I have included var db = require('../config/db'); and within ...

Retrieve a selection of data from the data.json file and mix it up

My webpage has a json data sheet containing multiple objects that I am currently showcasing. { "objects": [ ... ] } In terms of templating: $(function () { $.getJSON('data.json', function(data) { var template = $('#objectstpl') ...

What is the best way to remove an object from a complex JavaScript array structure?

I'm having trouble removing an object from the array provided below. Whenever I try to delete its properties, they just turn into undefined. I have a recursive function that correctly identifies the object I want to remove. Specifically, I need to eli ...

Serialization of HTML form containing embedded objects

There is a form on my website that includes fields for address and dimensions. Here is an example of the form structure: <form id="my-form"> <fieldset name="address"> <input name="streetAddress" type="text" placeholder="Street Addres ...

Encountering a ReferrenceError when utilizing jQuery with TypeScript

After transitioning from using JavaScript to TypeScript, I found myself reluctant to abandon jQuery. In my search for guidance on how to integrate the two, I came across several informative websites. Working with Visual Studio 2012, here is my initial atte ...

Adjusting the value of 'let' based on the outcome

Can you assist me with this issue? I am attempting to assign a value to a let variable based on the following if conditional block. class Main extends React.Component{ render(){ let content = ''; firebase.auth().onAuthStateChanged(func ...

Transitioning background color on hover using HTML and CSS styling techniques

My goal is to change the background color of an element when the cursor hovers over it. Oddly enough, the transition is successful for altering the font size but not for the background color. Here is my CSS code: .ul01 a,p{ height: 100%; display: ...

Search through a JSON array to find a specific element and retrieve the entire array linked to that element

Recently, I've been working with a json array that dynamically increases based on user input. Here's a snippet of the json code I'm dealing with: [{"scheduleid":"randomid","datestart":"2020-06-30",&quo ...

Enhance your HTML input form with Bootstrap by adding more options

I am currently using a form to gather user input in order to save specific information, such as instructions for a receipt. The challenge I'm facing is that I would like to have an unlimited number of fields for these instructions, instead of the fixe ...

Arranging several lists in columns with a customized header title

I am looking to have 7 lists displayed side by side, each with a unique styled header title. I want the lists to be neatly organized under their respective titles, including the bullets. I attempted to use text-indent for this purpose, but it seems that ...

How to insert a new document into a MongoDB collection with Mongoose

Consider a scenario where my existing collection called fruits is structured as follows: {"_id" : ObjectId("xyz...."), "name" : "Apple", "rating" : 7} {"_id" : ObjectId("abc...."), " ...

Check for the presence of a horizontal scrollbar on the page for both computer and mobile devices

Is there a way to determine if a web page has a horizontal scrollbar using jQuery or pure JavaScript? I need this information to dynamically change the css of another element. I initially tried function isHorizontalScrollbarEnabled() { return $(docum ...

The Unicode range [uXXXX] in Regex is not recognized during the AJAX request

I am currently facing an issue with removing control characters (e.g. \u0005) from the ajax response string. I have implemented a regular expression for this purpose: msg = msg.replace(/[\x00-\x1F\x7F-\x9F]/g, ''); Inter ...

I need to find a way to properly test a recursive, async JavaScript function by utilizing fake timers

I've been working with a basic recursive function that performs as expected when run. To thoroughly test its operation at each stage, I want to utilize Sinon's fake timers. Unfortunately, it seems that the fake timers are only affecting the init ...

Eliminate the error notification on the login page if it corresponds to the input

I am facing an issue with my login page and the API for password validation. Even when the password matches, an error message is still being displayed. This is because I am looping through the data and need to break the loop once a match is found. How can ...

Is there a secure alternative in Typescript for handling null values, such as a "safe operator"?

I'm currently working on implementing a feature in my Angular application where I need to toggle the visibility of a div using ngIf. Below you can find the snippet of HTML code I am using: <div *ngIf="damageReportToPolice()"> </div> Her ...

How can I redirect to a different URL using Ajax when successful POST request is made?

Here is the code snippet I am working with: $.ajax({ type: "POST", url: "/pro_signup", data: { data: data, key: key }, dataType: "json", success: function (response) { document.getElementById("pu ...

Adding a Data Attribute to Bootstrap 5 Popovers

I'm facing an issue with a group of buttons that have a data-attribute I want to include in the popover they trigger. HTML: <button type="button" class="btn btn-yellow btn-deleteTeacher" data-bs-toggle="popover" role= ...