简体   繁体   English

您如何使用jQuery获取选择表单输入的值?

[英]How do you use jQuery to get the value of an input of a select form?

I set up this example code to try and track the problem in my bigger website, but I don't understand why the value keeps coming back as undefined. 我设置了此示例代码,以尝试在较大的网站上跟踪问题,但我不明白为什么该值会不断返回未定义状态。

<script>
    function echo(){
        value = $('input[name=select_form]').val();
        $(document).ready(function(){
                $('#test_div').append("<p>" + value + "</p>"); 
            })          
        }
</script>

</head>

<table>
    <tr>
        <td>select an option</td>
        <td><select name = "select_form">
                <option value="Alpha">Alpha</option>
                <option value="Beta">Beta</option>
             </select>
        </td>
    </tr>
</table>

<input type='button' value='echo' name='submitbtn' onclick='echo()' />

<div id = "test_div"> </div>

Your selector is wrong, you are targeting a select element, not an input element 您的选择器错误,您定位的是select元素,而不是input元素

value = $('select[name=select_form]').val();

Demo: Fiddle 演示: 小提琴

Note: also there is no need for dom ready handler - if you want to use it then use a proper jQuery event handler inside a dom ready handler 注意:也不需要dom ready处理程序-如果要使用它,请在dom ready处理程序内使用适当的jQuery事件处理程序

<input type='button' value='echo' name='submitbtn' />

then 然后

jQuery(function () {
    $('input[name="submitbtn"]').click(function () {
        var value = $('select[name=select_form]').val();
        $('#test_div').append("<p>" + value + "</p>");
    })
})

Demo: Fiddle 演示: 小提琴

我认为$('select[name=select_form] option:selected').text()将起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM