skip to Main Content

I have a piece of code that obtains 10 input values (integers and floats) from the user:

var in1 = parseInt(document.getElementById("in1").value);
var in2 = parseInt(document.getElementById("in2").value);
var in3 = parseFloat(document.getElementById("in3").value);
var in4 = parseFloat(document.getElementById("in4").value);
var in5 = parseInt(document.getElementById("in5").value);
var in6 = parseInt(document.getElementById("in6").value);
var in7 = parseInt(document.getElementById("in7").value);
var in8 = parseFloat(document.getElementById("in8").value);
var in9 = parseFloat(document.getElementById("in9").value);
var in10 = parseInt(document.getElementById("in10").value);

I then put all inputs into an array, such that they are easier to work with:

var arr = [in1, in2, in3, in4, in5, in6, in7, in8, in9, in10];

And the idea is to adjust the CSS of an HTML container by iterating through the values, and adjusting the specific container, whose value is equal to 0.

for (let i = 0; i < arr.length; i++) {
    if (arr[i] === 0) {
        document.getElementById(**container of the corresponding arr[i] value**).style.color = "red";
    } else {
        document.getElementById(**container of the corresponding arr[i] value**).style.color = "black";
    }
}

Now how can I solve this?

I can get the code to run, if I just work with one container, say in1, so if I put ("in1") instead of the

(**container of the corresponding arr[i] value**)

4

Answers


  1. way too complicated. Give them all the same class and select them all with querySelectorAll. Then use forEach to iterate over all those elements. Use a ternary conditional operator to apply the color:

    /* runs the function if the DOM is parsed */
    window.addEventListener('DOMContentLoaded', function() {
      /* gets all the inputs */
      const INPUTS = document.querySelectorAll('input');
      
      function checkInputs() {
        INPUTS.forEach(input => {
          let value = parseFloat(input.value);
          input.style.color = (value === 0) ? 'red' : 'black';
        })
      };
      
      /* excutes the check at the start */ 
      checkInputs();
      
      /* executes the check again if a change within the inputs has been made */
      INPUTS.forEach(el => 
        el.addEventListener('change', checkInputs)
      );
    })
    /* for visualization purpose only */
    input {
      width: 5em;
      display: block;
      margin-bottom: 0.5em;
    }
    <input type="number" id="in1" value="0">
    <input type="number" id="in2" value="5">
    <input type="number" id="in3" value="0">
    <input type="number" id="in4" value="5">
    <input type="number" id="in5" value="5">
    <input type="number" id="in6" value="0">
    <input type="number" id="in7" value="0">
    <input type="number" id="in8" value="5">
    <input type="number" id="in9" value="0">
    <input type="number" id="in10" value="0">
    Login or Signup to reply.
  2. EDIT: When possible follow @tacoshy ‘s answer


    First I would make an array of objects with values, parser and element
    Where parser is the parser to convert the value from your HTML element (parseInt or parseFloat). And where element is the HTML/DOM element, so you don’t have to call document.getElementById too much, because it is not performant to use it every time you need it.

    const arr = [
        { parser: parseInt, element: document.getElementById("in1") },
        { parser: parseInt, element: document.getElementById("in2") },
        { parser: parseFloat, element: document.getElementById("in3") },
        { parser: parseFloat, element: document.getElementById("in4") },
        { parser: parseInt, element: document.getElementById("in5") },
        { parser: parseInt, element: document.getElementById("in6") },
        { parser: parseInt, element: document.getElementById("in7") },
        { parser: parseFloat, element: document.getElementById("in8") },
        { parser: parseFloat, element: document.getElementById("in9") },
        { parser: parseInt, element: document.getElementById("in10") },
    ];
    

    When you want to set te color, you can loop over it by using the js for-of loop, where we also use the ES6 object destructuring to get the parser and the element as a variable.

    Then we use the parser with the value of the element to parse it into a number.

    for (const { parser, element } of arr) {
        let color = "black";
    
        if (parser(element.value) === 0) {
            color = "red";
        }
    
        element.style.color = color;
    }
    
    Login or Signup to reply.
  3. You could select all inputs by class and then iterate over them. adding an event listener on keyup or on change. within the event callback you can change the colour based on the conditions you wish to check. In this example the text in the input canges colour based on the length of the value.

    const inputs = document.getElementsByClassName("colorInput")
    
    for (let i = 0; i < inputs.length; i++) {
      inputs[i].addEventListener (
        "keyup",
        (event) => {
          event.target.style.color = event.target.value.length > 10 ? "red" : "green"
        }
      )
    }
    <input type="text" class="colorInput">
    <input type="text" class="colorInput">
    <input type="text" class="colorInput">
    <input type="text" class="colorInput">
    Login or Signup to reply.
  4. At my opinion…
    If some values are parseFloat and others parseInt, this will cause a problem if you want to add an event to update the colors when the value change.

    For the parseInt values the color will stay red until you reach an int number (1 or -1 in this case) but there will be no problem with the float numbers (0.1, 0.2, 0.3, 0.4, 0,5 … 0.9) or negative (-0.1, -0.2, -0.3, -0.4, -0,5 … -0.9).

    When using parseInt(), any non-integer value will be converted to 0

    Here is a snippet even it’s not elegant, you’ll understand the problem when you change values.

    The options in the input field step="0.1" min="-10" max="10"are optional.

    The first snippet is there just to understand the mistakes, there’s another snippet under the first one that solve the issue.

            let elements_values=[];
            function getHTMLElements(){
                for (var i=1; i <=10; i++){
                    var el = "in" + i;
                    elements_values.push({element:document.getElementById(el),value:0,id:i-1});
                    element:document.getElementById(el).addEventListener("change",dealChange);
                }
            }
            //getElementsValues is not suitable (see snippet 2)
            function getElementsValues(){
                elements_values[0].value = parseInt(elements_values[0].element.value);
                // the value is 0.9 but with parseInt this element will display a red style
                // if you change the value to 1 it will become black again
                elements_values[1].value = parseInt(elements_values[1].element.value);
                elements_values[2].value = parseFloat(elements_values[2].element.value);
                // the value is 0.3 and due to parseFloat this element will display a black style
                elements_values[3].value = parseFloat(elements_values[3].element.value);
                //  the value is 0 and due to parseFloat this element will display a red style
                // a black style will be used if you change the value OK
                elements_values[4].value = parseInt(elements_values[4].element.value);
                elements_values[5].value = parseInt(elements_values[5].element.value);
                elements_values[6].value = parseInt(elements_values[6].element.value);
                //  the value is 0 and due to parseFloat this element will display a red style
                // a black style will be used if you change the value OK
                elements_values[7].value = parseFloat(elements_values[7].element.value);
                elements_values[8].value = parseFloat(elements_values[8].element.value);
                elements_values[9].value = parseInt(elements_values[9].element.value);
                // the value is -0.6 but with parseInt this element will display a red style
            }
            // see the other snippet to change this function.
            function logObjects(){
                for (var i=0; i <10; i++){
                    console.log("element = " + elements_values[i].element + " value = " + elements_values[i].value + " id = " + elements_values[i].id);
                }
            }
            function styleObject(){
                for (var i = 0; i < elements_values.length; i++) {
                    if (elements_values[i].value === 0) {
                        elements_values[i].element.style.color = "red";
                        elements_values[i].element.style.backgroundColor = "#cccccc";
                        elements_values[i].element.style.fontWeight = "bold";
                    } else {
                        elements_values[i].element.style.color = "black";
                        elements_values[i].element.style.backgroundColor = "#eeeeee";
                        elements_values[i].element.style.fontWeight = "normal";
                    }
                }
            }
            function dealChange(e){
                getElementsValues();
                styleObject();
            }
            getHTMLElements();
            getElementsValues();
            //logObjects();
            styleObject();
        <input id="in1" type="number" value="0.9" step="0.1" min="-10" max="10">
        <input id="in2" type="number" value="2" step="0.1" min="-10" max="10">
        <input id="in3" type="number" value="0.3" step="0.1" min="-10" max="10">
        <input id="in4" type="number" value="0" step="0.1" min="-10" max="10">
        <input id="in5" type="number" value="1.5" step="0.1" min="-10" max="10">
        <input id="in6" type="number" value="6.67" step="0.1" min="-10" max="10">
        <input id="in7" type="number" value="0" step="0.1" min="-10" max="10">
        <input id="in8" type="number" value="8.02" step="0.1" min="-10" max="10">
        <input id="in9" type="number" value="9.88" step="0.1" min="-10" max="10">
        <input id="in10" type="number" value="-0.6" step="0.1" min="-10" max="10">

    Here You will not have the same problem and the code is shorter.
    This is the snippet that solve the issue in case of numbers such :
    0,1 to 0,9:

    The following code involves an array of objects to store the elements, their values, and their IDs, and four functions to get the HTML elements, get their values, log the objects, and style the objects based on their values.

    I know that this code is more difficult to read than tacoshy’s answer but may be more flexible and can be extended to handle more elements and more complex logic. However, it may be overkill for this specific use case.

    let elements_values=[];
            function getHTMLElements(){
                for (var i=1; i <=10; i++){
                    var el = "in" + i;
                    elements_values.push({element:document.getElementById(el),value:0,id:i-1});
                    element:document.getElementById(el).addEventListener("change",dealChange);
                }
            }
            function getElementsValues(){
                for (var i=0; i <10; i++){
                    elements_values[i].value = parseFloat(elements_values[i].element.value);
                }
            }
            function logObjects(){
                for (var i=0; i <10; i++){
                    console.log("element = " + elements_values[i].element + " value = " + elements_values[i].value + " id = " + elements_values[i].id);
                }
            }
            function styleObject(){
                for (var i = 0; i < elements_values.length; i++) {
                    if (parseFloat(elements_values[i].value) === 0) {
                        //elements_values[i].element.style.color = "red";
                        //elements_values[i].element.style.backgroundColor = "#cccccc";
                        //elements_values[i].element.style.fontWeight = "bold";
                        // or we can also just comment the lines elements_values[i].element.style since the styles are defined ... and change it by the following line like this :
                        elements_values[i].element.className = "equalZero";
                    } else {
                        //elements_values[i].element.style.color = "black";
                        //elements_values[i].element.style.backgroundColor = "#eeeeee";
                        //elements_values[i].element.style.fontWeight = "normal";
                        // or we can also just comment the lines elements_values[i].element.style since the styles are defined ... and change it by the following line like this :
                        elements_values[i].element.className = "notEqualZero";
                    }
                }
            }
            // by modifying the method styleObject() this way :
            // elements_values[i].element.className = "yourClass"
            // it's shorter an easier to modify the style 
            function dealChange(e){
                getElementsValues();
                styleObject();
            }
            getHTMLElements();
            getElementsValues();
            //logObjects();
            styleObject();
            .equalZero {
              color: red;
              background-color: #cccccc;
              font-weight: bold;
            }
            .notEqualZero {
              color: black;
              background-color: #eeeeee;
              font-weight: normal;
            }
        <input id="in1" type="number" value="0.9" step="0.1" min="-10" max="10">
        <input id="in2" type="number" value="2" step="0.1" min="-10" max="10">
        <input id="in3" type="number" value="0.3" step="0.1" min="-10" max="10">
        <input id="in4" type="number" value="0" step="0.1" min="-10" max="10">
        <input id="in5" type="number" value="1.5" step="0.1" min="-10" max="10">
        <input id="in6" type="number" value="6.67" step="0.1" min="-10" max="10">
        <input id="in7" type="number" value="0" step="0.1" min="-10" max="10">
        <input id="in8" type="number" value="8.02" step="0.1" min="-10" max="10">
        <input id="in9" type="number" value="9.88" step="0.1" min="-10" max="10">
        <input id="in10" type="number" value="-0.6" step="0.1" min="-10" max="10">

    I made a lot of edits in this answer to add the comments in the getElementsValues()function in the first snippet and to do my best to explain what were the issues with the first code.

    I hope that the other explanations will help you to understand as precisely as possible the different cases and their implications.

    Best regards.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search