jquery not getting value from select statement on change

一笑奈何 提交于 2019-12-12 03:27:44

问题


This is really odd, but I am probably missing something simple. I have a simple select statement where a user can choose a value.

onChange calls a function getDrop2() which currently I am trying to get it to alert me which option is chosen.

my html is:

<select  onChange= "getDrop2()" id = "drop1" >
     <option value="0">All</option>
     <option value="1">Alphabetical</option>
     <option value="2">Brewery</option>
     <option value="3">Style</option>
</select>

My Javascript is:

function getDrop2(){
    var choice = $("#drop1").val()
    alert(choice);

}

The output of the alert statement is just blank.


回答1:


In jQuery, you're better off doing something like:

<select id = "drop1" >
     <option value="0">All</option>
     <option value="1">Alphabetical</option>
     <option value="2">Brewery</option>
     <option value="3">Style</option>
</select>

With the following JavaScript:

 $(function(){
    $('#drop1').change(function() {
        var choice = $(this).val();
        alert(choice);
    }
  });

The idea is that jQuery is now attaching the change function automatically to the select with the id of "drop1" By using this pattern, you've decoupled the HTML from the JavaScript that's doing the business logic.




回答2:


Although what others have selected is a better approach. My answer is just to tell you why your code is not working

Try this

var choice = $('#drop1 option:selected').val()

Instead of

var choice = $("#drop1").val()


来源:https://stackoverflow.com/questions/14822476/jquery-not-getting-value-from-select-statement-on-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!