使用 JQuery 从文本输入动态创建复选框 [英] Dynamically create checkbox with JQuery from text input
问题描述
在我的 cms 中,我有一个用于类别的复选框组.我想在下面有一个文本输入,用户可以在其中输入新类别的名称,它会动态添加一个新复选框,其中提供的名称用于值和标签.
我该怎么做?
<input type="checkbox" value="first checkbox" id="cb1"/><label for="cb1">第一个复选框</label><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());});});功能 addCheckbox(名称){var container = $('#cblist');var input = container.find('input');var id = input.length+1;$('<input/>', { type: 'checkbox', id: 'cb'+id, value: name }).appendTo(container);$('<label/>', { 'for': 'cb'+id, text: name }).appendTo(container);}
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.
How can I do this?
<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>
这篇关于使用 JQuery 从文本输入动态创建复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!