treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Problems with trying to get the "text" of a drop down option

  • With some help from the community here, i was able to successfully get a jQuery function to grab the "val" of a selection of a drop down and do a conditional test with that value.

    However the problem with using the <option value=""> is that the value is dynamically created and can be any number. So I have to use the text between the <option value=""></option> which doesn't ever change. However, I cannot successfully obtain that text (.text()).

    Details:
    - Drop down with: class="choice"
    - Drop down contains to options: "Someone Else" and "Me" as your two choices
    - By default the drop down has "Me" selected. I need to see when the drop down changes (.change(function()) if "Someone Else" was selected.

    NOTE: I have an alert ( ) there to return what is in the variable so I can see myself and it always returns blank.

    Here is my attempted code:

    <script type=\"text/javascript\">
    jQuery.noConflict();
    jQuery(document).ready(function(){
    jQuery(\".optional-field\").hide();
    jQuery(\".warning\").hide();

    jQuery(\".choice\").change(function() {
    var choice = jQuery(\".choice:selected\").text();

    alert ( choice );
    if (choice == 'Me') {
    jQuery(\".optional-field\").hide();
    jQuery(\".warning\").hide('slow');
    } else if (choice == 'Someone Else') {
    jQuery(\".optional-field\").show('slow');
    jQuery(\".warning\").show('slow');
    }
    });
    });

    </script>
  • Ok, so I made the following change and the variable "choice" now returns a value when the drop down selection changes. But the value of variable "choice" still doesn't meet one of the two conditions ("Me" and "Someone Else"). The other oddity is that when I put in a "alert (choice)" to return the value it got it puts "Me" or "Someone Else" to the far right of the alert window.

    My changes


    jQuery(\".choice\").change(function() {
    var choice = jQuery(\".choice option:selected\").text();
    alert (choice);