Home > OS >  How do I get multiple outputs from a 2D array using radio buttons?
How do I get multiple outputs from a 2D array using radio buttons?

Time:01-27

I am creating a webpage that allows users to search for a hiking trail based on difficulty. They will select either the 'Easy' or 'Hard' radio button and will be provided with a corresponding trail.

Here is my HTML:

Hiking NL!
<meta content="width=device-width, initial-scale=1" name="viewport" />
<link rel="stylesheet" type="text/css" href="style.css">
<p> Select Difficulty:</p>

<form>
    <fieldset>
        <input type="radio" id="easy" name="difficulty" value="Easy"> Easy
        <br>
        <input type="radio" id="hard" name="difficulty" value="Hard"> Hard
        <br>
    <div id="button">
        <button type="button" onclick="displayArray()">Find a Hike!</button>
    </div>
    </fieldset>
</form>

<script src="src/index.js"></script>

I have stored the trail names, along with the difficulty and length in a 2D array. I have been able to make it so one trail name will appear with each radio button, but when I add another 'Easy' trail to the array, only one name will show up. It looks like it is skipping over the first row of the array. How do I get it to output multiple trail names?

This is my script:

//Allows console.log to display what radio button was selected.
let chosen;

document.getElementById('easy').onclick = function () {
    console.log("Easy")
    chosen = "Easy";
}
document.getElementById('hard').onclick = function () {
    console.log("Hard")
    chosen = "Hard";
}

function displayArray() {

//Two dimensional array

    let hikes = [
        ['Easy','Silver Mine Head Path', 5],
        ['Hard','White Horse Path', 4],
        ['Easy','Father Troy', 3]
    ];
        console.log(hikes)
      
    let results = [];
    console.log(results);

    for(i = 0; i < hikes.length; i  ) {

              if(hikes[i][0] == chosen){  //Checks row for difficulty
                console.log("Row: " chosen)

                    results[i] = hikes[i][1]; //Shows corresponding hike with chosen difficulty

                                document.getElementById("output").innerHTML //Shows users their result
                                = "Trail: " results[i];


                            }
                        }
                           
                    }

CodePudding user response:

Try replacing your for loop with this:

for (i = 0; i < hikes.length; i  ) {
  if (hikes[i][0] == chosen) {
    //Checks row for difficulty
    console.log("Row: "   chosen);

    results.push(hikes[i][1]); //Shows corresponding hike with chosen difficulty
  }
}

document.getElementById("output").innerHTML = "Trail(s): "   results.join(", "); //Shows users their result
  • Related