取消选中复选框后,输入类型文本字段将重复
我有一个名为Firstname,Lastname和Email的复选框。我必须在单击复选框后显示输入类型,或者如果未选中,则删除复选框。
I have check boxes called as Firstname, Lastname and Email. I have to display the input type after clicking on the check box or if unchecked then remove the check box.
此外,我正在尝试获取复选框的标签已被选中,但我没有得到它。
Also, I am trying to get the label of check box which is selected but I am not getting it.
你会帮助我吗?
$(document).ready(function() {
$(".add_text_type").click(function() {
if ($('.add_text_type').is(":checked")) {
var get_label = $('label[for="' + +$(this).attr('id') + '"]').text();
$("#items").append('<div><label class=' + get_label + '></label><input type="text" name="input[]"></div>');
} else {
//what login I have to use here when unchecked check box
}
});
});
$(document).ready(function() {
$(".add_email_type").click(function() {
if ($('.add_email_type').is(":checked")) {
$("#items").append('<div><input type="email" name="input[]"></div>');
} else {
//what login I have to use here when unchecked check box
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="check-fields" class="add_text_type" id="get_first_name">
<label for="get_first_name">First Name</label>
<input type="checkbox" name="check-fields" class="add_text_type" id="get_last_name">
<label for="get_last_name">Last Name</label>
<input type="checkbox" name="check-fields" class="add_email_type" id="get_email">
<label for="get_email">Email</label>
最简单的方法是给 div
您将复选框的 id
附加为类
的元素,以便在需要时可以轻松识别它们删除它们。
The simplest way to do this would be to give the div
elements that you append the id
of the checkbox as a class
, so that they can be easily identified when you need to remove them.
您还可以通过提供输入
的类型
来干掉代码在复选框上添加 data
属性,可以在更改
事件处理程序中读取,如下所示:
You can also DRY up the code by providing the type
of the input
to add as a data
attribute on the checkbox which can be read in the change
event handler, like this:
$(function() {
$(".add_input").change(function() {
if (this.checked) {
$("#items").append('<div class="' + this.id + '"><input type="' + $(this).data('type') + '" name="input[]" placeholder="' + $(this).next('label').text() + '" /></div>');
} else {
$('#items').find('.' + this.id).remove();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="check-fields" class="add_input" id="get_first_name" data-type="text">
<label for="get_first_name">First Name</label>
<input type="checkbox" name="check-fields" class="add_input" id="get_last_name" data-type="text">
<label for="get_last_name">Last Name</label>
<input type="checkbox" name="check-fields" class="add_input" id="get_email" data-type="email">
<label for="get_email">Email</label>
<div id="items"></div>