简体   繁体   中英

Select option from dropdown menu and show data about it on the same page

I'm currently learning html, css, javascript and I'm making a simple project where the user selects an option from the drop-down menu. There is some data about that option in an array. I would like to output that data on the same page but a bit on the right-hand side of the page.

I'm kind of stuck outputting the data associated with the option from the drop-down menu. When you select an option from drop-down menu, all the data comes out on the screen while I would like only one piece of data per drop-down option ie choosing Apple showing Apple data only.

Preferably not jquery just pure javascript at the moment.Thanks

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=<device-width>, initial-scale=1.0">
  <title>Document</title>
  <style>
    .hide{
        display: none;
    }
    .show{
        display:block;
    }
  </style>
</head>
<body>
  <main>
    <article>
      <h1>List</h1>
      <div>
        <select name="food" id="food" onchange="changeVal()">
          <option value=""selected>Select One</option>
          <option value="Apple">Apple</option>
          <option value="Chocolate">Chocolate</option>
          <option value="Banana">Banana</option>
          <option value="All">All Food</option>
        </select>
      </div>
      <div id="chosenFood" class="hide">
        <h1 style = "text-align:center;">Food List</h1>
        <div id="showFoodList"></div>
      </div>
    </article>
  </main>
<script>
  function changeVal()
  {
    var f = document.getElementById("food");
    var chosenFood = f.options[f.selectedIndex].value;
    document.getElementById("chosenFood").value=chosenFood;
    document.getElementById("chosenFood").className="show";
  }
  var foodInfo = [{
    "Name" : "Apple",
    "Colour" : "Green"
  },
  {
    "Name" : "Chocolate",
    "Colour" : "Brown"
  },
  {
    "Name" : "Banana",
    "Colour" : "Yellow"
  }];
  function showFood(info)
  {
    var out="";
    for(var i=0;i<info.length;++i)
    {
      out+='<label>Name: '+info[i].Name +'<br></label>' +
      '<label>Name: '+info[i].Colour +'<br></label><br>'

    }
    document.getElementById("showFoodList").innerHTML=out;
  }
  showFood(foodInfo);
</script>
</body>
</html>

Your issue is in this line:

document.getElementById("chosenFood").value=chosenFood;

A div doesn't have a value but you can use the property innerHTML in order to add something to a div. In any case I assume you wish to add a new paragraph to the inner div, the one with the id showFoodList .

In any case I would suggest to use .addEventListener() to attach an event handler to an element.

The fixed code is:

 function changeVal() { var f = document.getElementById("food"); var chosenFood = f.options[f.selectedIndex].value; document.getElementById("showFoodList").innerHTML += '<p>' + chosenFood + '</p>'; document.getElementById("chosenFood").className="show"; }
 .hide{ display: none; }.show{ display:block; } #showFoodList { text-align: center; }
 <main> <article> <h1>List</h1> <div> <select name="food" id="food" onchange="changeVal()"> <option value=""selected>Select One</option> <option value="Apple">Apple</option> <option value="Chocolate">Chocolate</option> <option value="Banana">Banana</option> <option value="All">All Food</option> </select> </div> <div id="chosenFood" class="hide"> <h1 style = "text-align:center;">Food List</h1> <div id="showFoodList"></div> </div> </article> </main>

Your code and your explanations seem very confusing to me.
There is the need for different JS techniques, and I don't know where to start to explain my answer.
Don't hesitate to ask me anything about it!

First version

 const foodInfo = [ { Name: 'Apple', Colour: 'Green' }, { Name: 'Chocolate', Colour: 'Brown' }, { Name: 'Banana', Colour: 'Yellow' } ], selectFood = document.getElementById('food-select'), listFood = document.getElementById('food-list'), DomParser = new DOMParser(); function newItem(item) { let newItem = ` <article class="noDisplay" data-ref="${item.Name}"> <label> ${item.Name} </label> <label> ${item.Colour} </label> </article> ` return (DomParser.parseFromString(newItem, 'text/html')).body.firstChild } foodInfo.forEach(item=> { listFood.appendChild(newItem(item)) selectFood.add( new Option(item.Name, item.Name)) }) selectFood.add( new Option('All Food', 'All')) selectFood.querySelector('option').disabled = true const listArticles = listFood.querySelectorAll('article[data-ref]') selectFood.onchange=()=> { let choose = selectFood.value listArticles.forEach(art=> { if (choose==='All' || choose===art.dataset.ref) art.classList.remove('noDisplay') else art.classList.add('noDisplay') }) }
 .noDisplay { display: none;important: } #food-list { display; table: } #food-list article { display; table-row: } #food-list label { display; table-cell: padding. .2em;7em: } #food-list article:first-of-type { font-weight;bold; }
 <h3>List</h3> <select id="food-select" > <option value="" selected >Select One</option> </select> <h3>Food List</h3> <div id="food-list"> <article class=""> <label>Name:</label> <label>Colour:</label> </article> </div>

Note: this one use DOMParser.parseFromString() , which I find easier to insert multiple html lines with, multiple variables, on a page.

second version (with table)

To replace the articles and labels with a real table, here is the code. Note: there is also js directs methods for tables:

 const foodInfo = [ { Name: 'Apple', Colour: 'Green' }, { Name: 'Chocolate', Colour: 'Brown' }, { Name: 'Banana', Colour: 'Yellow' } ], selectFood = document.getElementById('food-select'), listFood_t = document.querySelector('table#food-list tbody'); foodInfo.forEach(item=> { // table listFood elements let row = listFood_t.insertRow() row.dataset.ref = item.Name row.insertCell().textContent = item.Name row.insertCell().textContent = item.Colour // food-select selectFood.add( new Option(item.Name, item.Name)) }) selectFood.add( new Option('All Food', 'All')) // last one... selectFood.querySelector('option').disabled = true const tableArticles = listFood_t.querySelectorAll('tr[data-ref]') tableArticles.forEach(el=>el.className='noDisplay') // none on start... selectFood.onchange=()=> { let choose = selectFood.value tableArticles.forEach(art=> { if (choose==='All' || choose===art.dataset.ref) art.classList.remove('noDisplay') else art.classList.add('noDisplay') }) }
 table { border-collapse: collapse; margin-top: .7em; } caption { font-size: 1.4em; font-weight:bold; } thead { background-color: #add8e6; font-weight:bold; } td { padding: .2em.7em; width: 8em; border: 1px solid grey; } tbody { text-align: right; }.noDisplay { display: none; }
 <h3>List</h3> <select id="food-select" > <option value="" selected >Select One</option> </select> <table id="food-list"> <caption>Food List</caption> <thead> <tr> <td> Name </td> <td> Colour </td> </tr> </thead> <tbody></tbody> </table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM