Flaffy Flaffy - 12 days ago 7
Javascript Question

Javascript, how do i search for an item in a textbox and receive it´s corresponding items in another textbox?

i can´t figure out how to search for a grade from the array below in a textbox and then receive all the names with that grade in a second textbox. So far when i search for a grade i don´t get a matching name. However when i just press the "getName" i do get a matching name and grade, but i want the ability to search for a specific grade myself and not just generate a random one. What do i need to change?

<html>
<head>
<script>
var mName = [
{Name: "Klara", Grade: "A"},
{Name: "Sarah", Grade: "A"},
{Name: "Andrea", Grade: "B"},
{Name: "Emil", Grade: "C"},
{Name: "Victor", Grade: "C"},
{Name: "Alicia", Grade: "D"},
{Name: "Thomas", Grade: "E"},
{Name: "Robert", Grade: "E"}
];

function getName(){
return mName[Math.floor(Math.random() * mName.length)]
}

function setValues(){
var tB1 = document.querySelector('#box');
var tB2 = document.querySelector('#box2');
var tName = getName();

tB1 && (tB1.value = tName.Name);
tB2 && (tB2.value = tName.Grade)
}
</script>
</head>

<body>
<form>

<input type="text" name="box2" id="box2" value=""/> <br/>
<input type="button" name="textbox1" id="textbox1" value="get Names" onclick="setValues()"/> <br/>
<input type="text" name="box" id="box" value=""/> <br/>
</form>
</body>



Answer

Here is another approach...

 <html> 
  <head> 
    <script>
        var  mName = [
                 {Name: "Klara", Grade: "A"},
                 {Name: "Sarah", Grade: "A"},
                 {Name: "Andrea", Grade: "B"},
                 {Name: "Emil", Grade: "C"},
                 {Name: "Victor", Grade: "C"},
                 {Name: "Alicia", Grade: "D"},
                 {Name: "Thomas", Grade: "E"},
                 {Name: "Robert", Grade: "E"}
        ];

        function getNames(grade) {

          var tmpStr = ''; // Will contain comma seperated value for input box

          for (var i = 0, len = mName.length; i < len; i++) {
            if(mName[i].Grade === grade) {
              tmpStr += mName[i].Name + ',';
            }
          }
            return tmpStr;
        }

        function setValues(){
            var tB1 = document.querySelector('#box');
            var tB2 = document.querySelector('#box2').value;
            tB1.value = getNames(tB2);          
        }
    </script>
</head>

    <body>
    <form>

        <input type="text" name="box2" id="box2" value=""/> <br/>
        <input type="button" name="textbox1" id="textbox1" value="get Names"     onclick="setValues()"/> <br/>
        <input type="text" name="box" id="box" value=""/> <br/>
    </form>
</body>