繁体   English   中英

如何为JQuery数组指定正确的列表?

[英]How can I specify the correct list for my JQuery array?

我在视图中有两个下拉列表,我试图将其中一个放入数组中。 第一个下拉列表名为'listOfDays',第二个下拉列表是'instructorString'。 由于某种原因,代码从两个列表中检索文本并将它们放入数组中。 如何为JQuery数组指定正确的列表? 这是脚本。 谢谢你的帮助。

        $(document).ready(function () {
            var trial = $('#instructorString').val();

            $('#saveBtn').click(function () {
                var checkList = new Array();
                $("select option:selected").each(function () {
                    if ($(this).is(':selected')) {
                        checkList.push($(this).val());

                    }
                    else
                        checkList.push('unchecked');
                });
                alert(checkList);
            });




        });

指定所需选择的ID ..并且您不需要is(:selected)部分,因为您的选择器option:selected选择仅选择的所有选项。

$('#saveBtn').click(function () {
            var checkList = new Array();
            $("#corectSelectID  option:selected").each(function () {
               // if ($(this).is(':selected')) { <---//you don't need this as the selector selects only selected option
                    checkList.push($(this).val());

            });
            console.log(checkList);
        });

如果您需要数组中未经检查的值,请选择选择器中的所有选项

  $('#saveBtn').click(function () {
            var checkList = new Array();
            $("#corectSelectID  option").each(function () {
               if ($(this).is(':selected')) 
                    checkList.push($(this).val());
               else
                    checkList.push('unchecked');

            });
            console.log(checkList);
        });

您只选择了所选的选项,因此检查is(':selected')没有意义的,因为它们都将被选中。 要选择所有选项并根据状态推送不同的值:

$(document).ready(function () {
     var trial = $('#instructorString').val();
     $('#saveBtn').on('click', function () {
         var checkList = [];
         $("select[name='listOfDays'] option").each(function () {
             if ($(this).is(':selected')) {
                 checkList.push( this.value );
             } else { // you where missing brackets
                 checkList.push('unchecked');
             }
         });
         //alert(checkList); You can't alert an array
         console.log( checkList )
     });
});

要根据名称选择一个select ,你需要$("select[name='listOfDays'] option")

而不是$("select option:selected")

尝试$('select.Class_of_Correctlist ')

$("select option:selected")将选择所有选定的下拉选项。

$("select.correctList option").each(function () { 
              //correctlist is the class for the correct drop down
             if ($(this).is(':selected')) {
                 checkList.push( this.value );
             } else { //
                 checkList.push('unchecked');
             }
         });

暂无
暂无

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

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