簡體   English   中英

使用JavaScript在動態創建的單選按鈕上顯示動態創建的文本框

[英]Display dynamically created text box on dynamically created radio button with JavaScript

我正在通過json接收一些數據,並根據輸入動態創建了一個表,該表根據輸入中的值顯示預選的單選按鈕(綠色/黃色/紅色)。 在第三列中,我將顯示一個注釋框。

現在,僅當黃色/紅色單選按鈕作為輸入或選擇時,我才想顯示注釋框。

這是我正在使用的代碼:

 $(document).ready(function() { var appStatus = [{ "category": "Overall Status", "status": "0" }, { "category": "System Availability", "status": "1" }, { "category": "Whatever", "status": "2" }]; var tr; for (var i = 0; i < appStatus.length; i++) { tr = $('<tr/>'); tr.append("<td>" + appStatus[i].category + "</td>"); tr.append('<tr id="row' + i + '"><td><input type="radio" name="inlineRadioOptions_' + i + '[]" value="0" id="inlineRadio0"' + (appStatus[i].status == '0' ? ' checked="checked"' : '') + '><font color="black">Grey &emsp;</font><label class="radio-inline"><input type="radio" name="inlineRadioOptions_' + i + '[]" value="1" id="inlineRadio1"' + (appStatus[i].status == '1' ? ' checked="checked"' : '') + '><font color="green">Green &emsp;</font><label class="radio-inline"><input type="radio" name="inlineRadioOptions_' + i + '[]" id="inlineRadio2" value="2"' + (appStatus[i].status == '2' ? ' checked="checked"' : '') + '><font color="yellow">Yellow &emsp;</font></label><label class="radio-inline"><input type="radio" name="inlineRadioOptions_' + i + '[]" id="inlineRadio3" value="3"' + (appStatus[i].status == '3' ? ' checked="checked"' : '') + '> <font color="red">Red</font></label><td></tr>'); //tr.append("<td>" + "<input>" + appStatus[i].comments + "</input>" + "</td>"); tr.append("<td>" + '<tr id="row' + i + '"><td><input type="text" id="appStatus[i].comments" name="appStatus[i].comments" placeholder="Comments" class="form-control name_list" required' + "</td>"); $('table').append(tr); } $('#result').on('click', function() { var new_status = []; $('.table tbody tr').each(function() { new_status.push({ category: $(this).find('td:eq(0)').text(), status: $(this).find(':radio:checked').val() }); }); console.log(new_status); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table class="table table-hover"> <thead> <th>Category</th> <th>Status</th> <th>Comments</th> </thead> </table> 

將處理程序添加到每個單選輸入。 由於您使用的是jQuery,因此附加的事件處理程序this作為事件源。 您必須分隔較長的<tr>...</tr>塊才能實現此目的。

一個簡單的例子:

table.append('<tr/>').append(
    $('<td>').append(
        $('<input type="radio" name="x">').change(function () {
            $(this).closest('td').find('input.comments').toggle(true or false);
        })
    )
)

...但是您可以變得更聰明,並使用變量將其寫得更加清晰。

另外,您還需要在代碼中的另一個元素內添加<tr>元素,這會導致HTML無效。 加上其他一些需要解決的小故障。

暫無
暫無

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

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