簡體   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