2017-09-05 116 views
3

我有名为Firstname,Lastname和Email的复选框。我必须在点击复选框后显示输入类型,或者如果未选中,请取消复选框。取消选中复选框后重复输入类型文本字段

此外,我想获取复选框的标签被选中,但我没有得到它。

你能帮我吗?

$(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>

+0

请在代码中添加带有id项的元素 – jANVI

回答

4

做到这将是当你需要删除给你追加复选框的idclassdiv元素,让他们可以很容易识别的最简单方法他们。

您也可以通过提供inputtype添加为上的复选框一个data属性,它可以在change事件处理程序来读取,这样干起来的代码:

$(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>

+0

它的工作非常好。感谢您的帮助。请在一分钟内感谢您的回复。 –

+0

我只想知道如果我必须使用选择类型,那我该如何使用它? –

+0

对于选择,您可能最好创建一个新函数,因为这是一个完全不同的HTML结构;不同的标签名称,属性,子元素等。 –