Tips for displaying specific information using Javascript depending on the input value of an HTML form

I am working on an HTML form that includes a dropdown list with four different names to choose from.

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

    function displaySelectedStudent(){
        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>

Upon clicking the submit button, a JavaScript function is called to display the name of the selected student. However, only the result of the first if statement is currently being displayed. I suspect that I need to pass the form data value into the function, but I am unsure how to accomplish this. Here is the current JavaScript code I have developed for this purpose.

Answer №1

To ensure the correct option is selected, make sure to utilize the value property instead of just setting it as "Mary Jones". By accessing the .value property of the <select> element, you can obtain the actual value of the selected option:

function displayStudent() {
    var chosen = document.getElementById("chooseStudent")["students"].value;
    var result = document.getElementById("selectedStudent");
    if (chosen == "mary jones") {
        result.innerHTML = "Mary Jones";
    } else if (chosen == "jane doe") {
        result.innerHTML = "Jane Doe";
    } else if (chosen == "henry miller") {
        result.innerHTML = "Henry Miller";
    } else {
        result.innerHTML = "John Smith";
    }
}

It's worth noting that ID names should not contain spaces - modify your <option> elements accordingly:

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

Answer №2

To obtain the chosen option from the list of options within the select element, extract the text content and display it.

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

function showStudents( e ) {
  e.preventDefault();
  var selectField = document.querySelector("select");
  var displayText = selectField.options[ selectField.selectedIndex ].innerText;
  document.getElementById("students").innerText = displayText;
}
<div id="students"></div>
<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>

Answer №3

There are several issues in your code that need to be addressed:

First of all, it is crucial to avoid assigning duplicate IDs to different elements within your HTML code. Each ID should be unique across the entire document to prevent unexpected errors when using functions like .getElementById().

Secondly, there is no necessity to provide IDs for <option> elements unless it serves a specific purpose. In this case, assigning IDs does not offer any benefits.

Thirdly, if you do decide to give IDs to <option> elements, avoid including spaces in the ID names as it can lead to undesirable outcomes.

Moreover, if your goal is simply to display the selected value, there is no need to use multiple if-else statements to handle each possibility individually. Utilizing a switch statement instead will improve the readability and conciseness of your code.

I have implemented some changes to your code based on these recommendations:

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

function showStudents() {

  var n = document.getElementById("sel_students");
  var name = n.options[n.selectedIndex].value;
  var output = document.getElementById("div_students");

  output.innerHTML = name;

  switch (name) {
    case "mary jones":
      output.innerHTML += "<br> Hi Mary..";
      break;
    case "jane doe":
      output.innerHTML += "<br> Goodbye Jane";
      break;
    case "henry miller":
      output.innerHTML += "<br> Good afternoon";
      break;
    case "john smith":
      output.innerHTML += "<br> No Pokahontis here";
      break;
  }


}
<div id="div_students">
  <form id="form_students" action="" method="GET">
    <select name="students" id="sel_students">
      <option value="john smith">John Smith</option>
      <option value="jane doe">Jane Doe</option>
      <option value="henry miller">Henry Miller</option>
      <option value="mary jones">Mary Jones</option>
    </select>
    <br><br>
    <input id="submit" type="submit">
  </form>
</div>

Answer №4

Please follow these steps

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

    function displayStudents(){
        document.getElementById("students").innerHTML = document.getElementById("student-list").value;
    }
<div id="students">
<form id="getStudent" action="" method="GET">
    <select name="students" id="student-list">
        <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>

Answer №5

What is the reason for not utilizing jQuery?

Retrieve it through id

var result = $('select#dropDownId option:selected').val();

Answer №6

<div id="classmates">
<form id="getClassmate" action="" method="GET">
    <select name="classmates" id="classmates_value">
        <option value="alex smith">Alex Smith</option>
        <option value="sarah doe">Sarah Doe</option>
        <option value="david miller">David Miller</option>
        <option value="lucy jones">Lucy Jones</option>
    </select>
    <br><br>
    <input id="submit" type="submit">
</form>

function displayClassmates(){
    var selected = document.getElementById("classmates_value");
    document.getElementById("classmates").innerHTML = selected;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue at hand: Unexpected error 500 encountered while sending AJAX request to PHP script through

UPDATE: Issue Resolved! I want to extend my gratitude to everyone who directed me to the error log files for assistance. The community here is truly incredible and I was able to get a resolution much quicker than anticipated. It's quite embarrassing, ...

obtain the string representation of the decimal HTML entity value

Similar Question: how to create iphone apps similar to ibeer, imilk, ibug, ibeer Using javascript to obtain raw html code Imagine having an html section like this: <div id="post_content"> <span>&#9654;<span> </div> ...

Is it possible to have scope inherit from an object in AngularJS?

Imagine creating an app like this: <script> myArray=<?php echo $array;?>; app={ myArray:myArray, myIndex:myArray.length-1, back:function(){this.myIndex--;console.log("You clicked back");}, forward:function(){this.myIndex++} } ...

Accessing JSON object with Javascript

I've been struggling with this code snippet and despite looking at similar posts, I can't seem to get it right. var obj2 = JSON.parse('{"venue_data": {"venue_id":"25", "description":"Space Cafe", "venue_type ...

How can you securely transfer the ARRAY OBJECT from JavaScript to PHP using Ajax?

I am attempting to send a Javascript Array Object via Ajax to PHP and then use that object as a true Array on the PHP side. My current approach has not been successful in terms of utilizing the incoming object as an Array within PHP; I can only parse it as ...

Issue with JavaScript-generated dropdown menu malfunctioning in WebView on Android devices

During my testing of the app on a Galaxy Tab with Android 2.2, I encountered an issue within the WebView component. The problem arises when I have a local HTML page generated dynamically and it contains a SELECT element like this: <select class='d ...

Creating a div that functions as a scrollbar controller

I am in search of a unique way to customize the scrolling functionality on my application, resembling more of a navbar that scrolls. However, I have not been able to find any existing plugins that meet my specific requirements. My inquiry includes: Whic ...

Troubleshooting server-side sorting issues with AJAX implementation, encountering problems with headers functionality

I'm encountering a problem: Some headers are not functioning properly to sort the table. For example, Brand and Model work as expected, but VehicleType only works once, and CarID and ReleaseDate never seem to work. Here is my index.php file: index. ...

Guide to changing the class of a particular child element when the parent element is clicked with vanilla JavaScript

Upon clicking the parent button, a class within its child element will toggle to show or hide. If the child element is selected, a loading animation will appear for a brief moment before reverting back to its original hidden state. I attempted to achieve ...

Tips for displaying buttons and images on the same line using CSS

Below is the JavaScript code I am using: $('#needdiv').append('<img src="/images/Connect.png" id="connectimage">' + '</img>' + '<input type="button" id="connect" value=connect >' + '&l ...

Is there a way to modify Style Properties in JavaScript by targeting elements with a specific class name using document.getElementsByClassName("Class_Name")?

I am seeking a solution to change the background color of multiple div boxes with the class name "flex-items" using JavaScript. Below is my current code: function changeColor(){ document.getElementsByClassName("flex-items").style.backgroundColor = "bl ...

Implementing a Timer on an HTML Page with JavaScript

I am looking to add a timer to my HTML page using JavaScript. The timer should get the selected date and time from an input field <input type="date" /> and control it. If the time difference between the current time and the selected time is less than ...

Is it possible to display multiple qTips for the same target using jQuery qTip2?

I am currently utilizing the jquery qtip2 plugin to generate a mouseover tooltip. Here is the code snippet I am using: $(document).ready(function() { $("#optionalProdsImgPreview_1").qtip({ content: "<img src='http://mysite.com/myimg.jpg&ap ...

"The boundary of suspense was updated before completing hydration." This error occurs when utilizing suspense and dynamic import within Next.js

I am currently working on lazy loading a list of data using suspense and dynamic import in Nextjs. However, I encountered the following error: Error: This Suspense boundary received an update before it finished hydrating. This caused the boundary to switch ...

Is it possible to track keystrokes without the use of text input fields?

For various unimportant reasons, I need to use JavaScript to create links instead of using the anchor tag. I want the behavior to mimic the anchor tag, allowing users to open a link in a new tab when holding down the Ctrl key or in a new window when holdin ...

Detecting Unflushed Requests in Jasmine and AngularJS

I'm encountering some issues passing certain tests after implementing $httpBackend.verifyNoOustandingRequest(). Interestingly, excluding this from my afterEach function allows the tests to pass successfully. However, including it causes all tests to ...

Hide the menu by clicking anywhere outside the React component

I'm working on a menu component that needs to close when clicking anywhere on the page while open. Is there a method to achieve this without having to add an event listener to the document and check the event.target? Unfortunately, I cannot send the ...

What steps can I take to ensure that the browser prints out a PDF copy of a webpage?

Imagine you have a website page saved as example.html, and also a printable file named example.pdf. Is there a way to prompt the browser to open and print example.pdf instead of example.html when users attempt to print? If this isn't achievable, how ...

leveraging array elements in the data and label properties of a chart.js chart

I would like to assign the values of an array to the data and label fields within a chart.js dataset. Below is the code executed upon successfully fetching JSON data using an AJAX call. The fetched JSON data is then stored in an array. Data = jQuery.pars ...

Converting CSS colors from RGBA to hexadecimal format: A step-by-step guide

Within my selenium code, I am faced with the challenge of verifying that the background color code is #192856. However, when obtaining the CSS property of the element, it returns the color in rgba format. How can I retrieve the values in hex format? quick ...