How to Get a Selected Value With jQuery

Drop-down boxes allow users to select an option in a Web form. Processing forms requires some programming outside of basic HTML code, but jQuery is well-suited to the challenge. Using the "val()" function, you can get the value of any selected page element. Write a function using the "click()" event to make the Web page display a drop-down or "selection" box value when the user clicks on a "Submit" button.

Instructions

    • 1

      Open your code in an editor such as Notepad or Notepad++, and check between the "<head>" tags and above the closing "</body>" tag for a jQuery library reference. Add this code if you find it in neither place:

      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>

      Add a new pair of "<script>" tags below that code. All of your jQuery code will go between these tags:

      <script type="text/javascript">

      </script>

    • 2

      Scroll down in your HTML code and find the ID names of the drop-down box, "Submit" button and an empty element where you can output the value:

      <form>

      <select id="dropdown">

      <option value="1">Value 1</option>

      </select>

      <input type="submit" value="Get the Value" id="mysubmit" />

      </form>

      <div id="thevalue"></div>

      In the example code above, the ID of the drop-down box is "dropdown" while the ID of the "Submit" button is "mysubmit." The "<div>" tags at the end have an ID of "thevalue," and you can use a div like this to output your drop-down value.

    • 3

      Go back to the script, and start your "document ready" function:

      $(function() {

      });

      Place your entire script inside this function. This code prevents the script from running until the page finishes loading.

    • 4

      Select the "Submit" button by its ID name, and append the "click()" function:

      $("#mysubmit").click(function() {

      });

      Change "mysubmit" to the ID name of your "Submit" button. Always append ID names with a hash symbol in jQuery selectors.

    • 5

      Declare a variable inside the "click()" function, and set it equal to a selector for your drop-down box with the "val()" function appended:

      var selection = $("#dropdown").val();

    • 6

      Select your empty HTML element, such as a pair of "<div>" tags, using its ID name. Append the "text()" function to this selector, and pass in your variable as its argument:

      $("#thevalue").text(selection);

    • 7

      Add "return false" to the end of your "click()" function to keep the "Submit" button from sending the user to another page. This is the final script:

      $(function() {

      $("#mysubmit).click(function() {

      var selection = $("#dropdown").val();

      $("#thevalue").text(selection);

      return false;

      });

      });

Related Searches:

References

Comments

Related Ads

Featured