簡體   English   中英

如何使用Javascript將帶有復選框的列表更改為下拉列表?

[英]How can I change a list with checkboxes to a dropdown list using Javascript?

我正在使用第三方軟件,但無權編輯頁面上的代碼,但是我可以添加Javascript來修改內容。 我正在尋找一種解決方案,可以幫助將復選框項目列表更改為下拉列表。 我以前很少有Java經驗。 提前致謝!

 <tr> <td class="BBFieldCaption DonationFieldCaption"> <label for="PC4519_214DIV" id="PC4519_lblLgnCtl214">Time Frame of Deduction:</label> </td> <td id="PC4519_ParentControl214" class="taLeft"> <DIV id="PC4519_214DIV" class="BBFormChecklistContainer LoginFormCheckListContainer"> <table id="PC4519_214" class="BBFormChecklist LoginFormCheckList"> <tr> <td> <input id="PC4519_214_0" type="checkbox" name="PC4519$214$0" value="PD Til Further Notice" /> <label for="PC4519_214_0">PD Til Further Notice </label> </td> </tr> <tr> <td> <input id="PC4519_214_1" type="checkbox" name="PC4519$214$1" value="Seahawk 3 Year Pledge" /> <label for="PC4519_214_1">Seahawk 3 Year Pledge </label> </td> </tr> <tr> ... etc ... </tr> </table> </div> </td> </tr> 

我不會為您編寫完整的js函數,但會指出一些有助於您的想法:

  1. 您可以參考答案以獲取td元素的值。 然后,您可以使用這些值來構建相關選項的數組。

     t = document.getElementById("table"), // This have to be the ID of your table, not the tag d = t.getElementsByTagName("tr")[0], r = d.getElementsByTagName("td")[0]; 
  2. 使用for循環(例如答案)從數組構建select下拉列表。

  3. 將您的html附加到DOM並刪除復選框列表,或使用replaceChild方法。

您需要做的第一件事是添加一個選擇元素。

我不確定您需要哪個容器元素,所以我選擇了主體。 您可以根據需要進行更改。

$('body').append('<select id="mySelc"></select>'); 

然后,收集所有復選框輸入元素。

var inpts = $('#PC4519_214').find('input[type="checkbox"]');

然后遍歷它們,取出需要的內容並將其附加到select元素。

$.each(inpts, function(ii,val){
    var optId = $(val).attr('id'), //pull out the id
        optVal = $(val).attr('value'), //pull out the value
        optData = $(val).attr('name'); // pull out the name. will be used as a data attribute.

    //append to the select element.
    $('#mySelc').append('<option id="'+optId+'" data="'+optData+'" value="'+optVal+'">'+optVal+'</option>');
});

我假設您使用的是jQuery,但是如果需要,我可以用純JavaScript重寫它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM