繁体   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