How to get Javascript to display specific data based on HTML form value

Tags: , , , ,



I have an html form that has a drop down list of four names.

    window.onload = function(){
        document.getElementById("submit").onclick = showStudents;
    }

    function showStudents(){
        if(document.getElementById("mary jones").value == "mary jones"){
            document.getElementById("students").innerHTML = "Mary Jones";
        }
        else if(document.getElementById("jane doe").value == "jane doe"){
            document.getElementById("students").innerHTML = "Jane Doe";
        }
        else if(document.getElementById("henry miller").value == "henry miller"){
            document.getElementById("students").innerHTML = "Henry Miller";
        }
        else if(document.getElementById("john smith").value == "john smith"){
            document.getElementById("students").innerHTML = "John Smith";
        }
    }
<div id="students">
<form id="getStudent" action="" method="GET">
    <select name="students">
        <option value="john smith" id="john smith">John Smith</option>
        <option value="jane doe" id="jane doe">Jane Doe</option>
        <option value="henry miller" id="henry miller">Henry Miller</option>
        <option value="mary jones" id="mary jones">Mary Jones</option>
    </select>
    <br><br>
    <input id="submit" type="submit">
</form>

When I click submit a Javascript function is called and I want to display the name of the student I chose but it only displays the results of the first if statement. My thought is that I need to pass in the value of the form data into the function but not sure how to do that. Here’s the javascript code I’ve come up.

Answer

You’ll need to use the selected option – currently, it’s only going to set it to “Mary Jones”, because the value of the <option id="mary jones" value="mary jones"> is always going to be “Mary Jones”. Use the .value property of the <select> element to get the selected option’s value:

function showStudents() {
    var selected = document.getElementById("getStudent")["students"].value;
    var output = document.getElementById("students");
    if (selected == "mary jones") {
        output.innerHTML = "Mary Jones";
    } else if (selected == "jane doe") {
        output.innerHTML = "Jane Doe";
    } else if (selected == "henry miller") {
        output.innerHTML = "Henry Miller";
    } else {
        output.innerHTML = "John Smith";
    }
}

Also keep in mind that you cannot have a space in an ID name – so your <option>s should look like this instead:

<option value="mary jones" id="maryJones">Mary Jones</option>


Source: stackoverflow