skip to Main Content

I have tried doing this, but it would display alert before showing what the user clicked for the radio button…
Should I remove the switch statement from the function?
Hopefully I can get this fixed because it seems like it works in other websites.
Ignore text in this sentence here because the post requires more ‘detail’ apparently.

"use strict";
window.onload = pageLoad;

function pageLoad(){
    var redButton = document.getElementById("red").onclick=colorChoice;
    var blueButton = document.getElementById("blue").onclick=colorChoice;
    var greenButton = document.getElementById("green").onclick=colorChoice;
    var yellowButton = document.getElementById("yellow").onclick=colorChoice;
    var orangeButton = document.getElementById("orange").onclick=colorChoice;
}

function colorChoice(){
    var userName = document.getElementById("nameBox").value;
    var color;
    var all_colors = document.getElementsByName("colorButton");
    for(var i = 0; i < all_colors.length; i++){
        if(all_colors[i].checked){
            color = all_colors[i].value;
        }
    }
    switch (color){
        case "red":
        alert("Hi " + userName + ", your favorite color is red");
        break;
        case "blue":
        alert("Hi " + userName + ", your favorite color is blue");
        break;
        case "green":
        alert("Hi " + userName + ", your favorite color is green");
        break;
        case "yellow":
        alert("Hi " + userName + ", your favorite color is yellow");
        break;
        case "orange":
        alert("Hi " + userName + ", your favorite color is orange");
        break;
        default:
        alert("There is an error");
        break;
    }
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <title> colors </title>
    <!-- add here the script tag to reference the Javascript file that will contain your event handler function -->
    
        <script type = "text/javascript"  src = "colors.js" >
  </script>
  </head>
  <body>
    <h4> Choose your favorite color </h4>
    <form id="colorsForm">
      <label>Enter your name: 
       <input type = "text"  name = "nameTextBox" id="nameBox" /> <br/>
      </label>
      <label> <input type = "radio"  name = "colorButton"  
                     value = "red" id="red" /> 
        Red </label>
      <br />
      <label>  <input type = "radio"  name = "colorButton"  
                      value = "blue" id="blue" /> 
        Blue </label>
      <br />
      <label> <input type = "radio"  name = "colorButton"  
                     value = "green" id="green" />      
         Green </label>
      <br />
      <label> <input type = "radio"  name = "colorButton"  
                     value = "yellow" id="yellow" />
         Yellow </label>
      <br />
      <label> <input type = "radio"  name = "colorButton"  
                     value = "orange" id="orange" />
         Orange </label>
    </form>
    </body>
</html>

2

Answers


  1. I think the switch should be removed

    If alert blocks window rendering, try adding a timer to solve the problem

    'use strict'
    window.onload = pageLoad
    const colors = ['red', 'blue', 'green', 'yellow', 'orange']
    function pageLoad() {
        colors.forEach(function (color) {
            document.getElementById(color).onchange = colorChoice
        })
    }
    function colorChoice() {
        var userName = document.getElementById('nameBox').value
        var color
        var all_colors = document.getElementsByName('colorButton')
        for (var i = 0; i < all_colors.length; i++) {
            if (all_colors[i].checked) {
                color = all_colors[i].value
            }
        }
        setTimeout(() => {
            if (colors.includes(color)) {
                alert('Hi ' + userName + ', your favorite color is ' + color)
            } else {
                alert('There is an error')
            }
        }, 10)
    }
    
    
    Login or Signup to reply.
  2. There are a few things here. You cannot make the radio button process click first (to reflect that it is selected) and only then run your action which is alert. Usually, such an approach is not needed because, in most cases, apps allow users to make all necessary choices on a form and then ask to click some kind of submit button to process all the selections.

    Another problem here is that the alert function is blocking JS code execution, and since JS is synchronous and single-threaded language, the radio button waits for the event to finish before it updates its look and becomes visually selected. alert is almost never used in a production environment because it cannot be styled and it is blocking, which is undesired in most cases.

    Therefore, if you want to stick to your approach, the best option to overcome blocking behavior is to delay alert with setTimeout, like so:

    setTimeout(() => alert("Hi " + userName + ", your favorite color is red"), 100);
    

    100 msec will be enough for the radio button to update before the alert is shown.

    I wouldn’t recommend using this approach on production and go with a HTML/CSS/JS based popup. There are plenty of tutorials (for example, this one) and JS libs/frameworks helping with this.

    However, if you are wondering how to achieve the same result with significantly less JS code, take a look at this option:

    const userNameInput = document.querySelector('#nameBox');
    const colorInputs = Array.from(document.querySelectorAll('input[name="colorButton"]'));
    
    const clickHandler = (event) => {
      setTimeout(() => {
        alert(`Hi ${userNameInput.value}, your favorite color is ${event.target.value}`);
      }, 100);
    };
    
    colorInputs.forEach((input) => input.addEventListener('click', clickHandler));
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <title> colors </title>
        <!-- add here the script tag to reference the Javascript file that will contain your event handler function -->
        
            <script type = "text/javascript"  src = "colors.js" >
      </script>
      </head>
      <body>
        <h4> Choose your favorite color </h4>
        <form id="colorsForm">
          <label>Enter your name: 
           <input type = "text"  name = "nameTextBox" id="nameBox" /> <br/>
          </label>
          <label> <input type = "radio"  name = "colorButton"  
                         value = "red" id="red" /> 
            Red </label>
          <br />
          <label>  <input type = "radio"  name = "colorButton"  
                          value = "blue" id="blue" /> 
            Blue </label>
          <br />
          <label> <input type = "radio"  name = "colorButton"  
                         value = "green" id="green" />      
             Green </label>
          <br />
          <label> <input type = "radio"  name = "colorButton"  
                         value = "yellow" id="yellow" />
             Yellow </label>
          <br />
          <label> <input type = "radio"  name = "colorButton"  
                         value = "orange" id="orange" />
             Orange </label>
        </form>
        </body>
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search