使用JQuery从文本输入动态创建复选框 [英] Dynamically create checkbox with JQuery from text input

查看:112
本文介绍了使用JQuery从文本输入动态创建复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的cms我有一个复选框组的类别。我想在下面有一个文本输入,用户可以输入一个新类别的名称,它会动态添加一个新的复选框与提供的名称用于值和标签。

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.

我该如何做?

推荐答案

<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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆