JQuery 选择值到变量中

JQuery select value into variable

本文关键字:变量 选择 JQuery      更新时间:2023-09-26

我已经看了一遍,无法弄清楚为什么这段代码不起作用。

http://jsfiddle.net/kCLxJ/

当下拉列表设置为值"3"或"4"时,下拉列表下方应弹出另一个字段。有什么想法吗?

jsFiddle

更改此设置:

var val = $('#event_options_id option:selected').html();

自:

var val = $('#event_options_id').val();

固定工作版本

首先,您需要像指出的那样致电.val()

var val = $('#event_options_id option:selected').val();

然后根据您使用的选择器,您需要在 val 上使用 parseInt() 以使其成为这样的数字

if ($.inArray(parseInt(val,10), arr) > -1) {

定义数组时还有一个额外的逗号。

完整的工作代码

$(document).ready(function() {
    $('#event_options_id').change(function() {
        $('.container_add_form').remove();
        var val = $('#event_options_id option:selected').val();
        var arr = [3, 4];
        if ($.inArray(parseInt(val,10), arr) > -1) {
            $('<input type="hidden" name="age_required" id="age_required" value="yes" /><div class="container_add_form"><p class="text_content">Please enter your age for grouping purposes.<br /><input name="age" type="text" id="age" size="3" /></p></div>').fadeIn('slow').appendTo('.add_form');
        }
    });
});​

1) 使用 .val() 而不是 .html() 来获取选项的值。

2)您正在将字符串值与数组中的数字进行比较,这将始终失败。

http://jsfiddle.net/kCLxJ/4/

var val = $('#event_options_id option:selected').val();
var arr = ['3', '4'];

更改这些行。

    var val = $('#event_options_id option:selected').val();
    var arr = ["3", "4"];

要获取组合框值,您必须使用"val()"而不是"html()"。并且您必须将数组的元素更改为字符串。变量 val 是一个字符串。inArray 将尝试以字符串而不是整数的形式查找元素。

我更新了你的代码:http://jsfiddle.net/kCLxJ/7/

$(document).ready(function() {
    $('#event_options_id').change(function() {
        $('.container_add_form').remove();
        // you used .text() but should've used .val()
        var val = $('#event_options_id option:selected').val();
        var arr = [3, 4];
        /*
            another problem was that you didn't parse the value into an integer
            but you were comparing the value to an array of integers
        */
        if ($.inArray(parseInt(val), arr) > -1) {
            $('<input type="hidden" name="age_required" id="age_required" value="yes" /><div class="container_add_form"><p class="text_content">Please enter your age for grouping purposes.<br /><input name="age" type="text" id="age" size="3" /></p></div>').fadeIn('slow').appendTo('.add_form');
        }
    });
});