使用 JQuery 从文本输入动态创建复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2055459/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically create checkbox with JQuery from text input
提问by Martin Reeves
In my cms I have a checkbox group for categories. I would like to have a text input below that where the user can input the name of a new category and it will dynamically add a new checkbox with the provided name used for both the value and the label.
在我的 cms 中,我有一个类别的复选框组。我想在下面有一个文本输入,用户可以在其中输入新类别的名称,它将动态添加一个新复选框,其中提供的名称用于值和标签。
How can I do this?
我怎样才能做到这一点?
回答by dxh
<div id="cblist">
<input type="checkbox" value="first checkbox" id="cb1" /> <label for="cb1">first checkbox</label>
</div>
<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />
<script type="text/javascript">
$(document).ready(function() {
$('#btnSave').click(function() {
addCheckbox($('#txtName').val());
});
});
function addCheckbox(name) {
var container = $('#cblist');
var inputs = container.find('input');
var id = inputs.length+1;
$('<input />', { type: 'checkbox', id: 'cb'+id, value: name }).appendTo(container);
$('<label />', { 'for': 'cb'+id, text: name }).appendTo(container);
}
</script>
回答by T. Stone
One of the elements to consider as you design your interface is on what event (when A takes place, B happens...) does the new checkbox end up being added?
在设计界面时要考虑的要素之一是新复选框最终会被添加到什么事件(当 A 发生时,B 发生时……)?
Let's say there is a button next to the text box. When the button is clicked the value of the textbox is turned into a new checkbox. Our markup could resemble the following...
假设文本框旁边有一个按钮。单击按钮时,文本框的值会变成一个新的复选框。我们的标记可能类似于以下内容...
<div id="checkboxes">
<input type="checkbox" /> Some label<br />
<input type="checkbox" /> Some other label<br />
</div>
<input type="text" id="newCheckText" /> <button id="addCheckbox">Add Checkbox</button>
Based on this markup your jquery could bind to the click
event of the button and manipulate the DOM.
基于此标记,您的 jquery 可以绑定到click
按钮的事件并操作 DOM。
$('#addCheckbox').click(function() {
var text = $('#newCheckText').val();
$('#checkboxes').append('<input type="checkbox" /> ' + text + '<br />');
});
回答by rahul
Put a global variable to generate the ids.
放置一个全局变量来生成 id。
<script>
$(function(){
// Variable to get ids for the checkboxes
var idCounter=1;
$("#btn1").click(function(){
var val = $("#txtAdd").val();
$("#divContainer").append ( "<label for='chk_" + idCounter + "'>" + val + "</label><input id='chk_" + idCounter + "' type='checkbox' value='" + val + "' />" );
idCounter ++;
});
});
</script>
<div id='divContainer'></div>
<input type="text" id="txtAdd" />
<button id="btn1">Click</button>