最初のdivとそれ以外はすべて削除します。 ここでコードスニペットで最初の入力を削除できますが、それ以上追加すると他の入力は削除できません。jqueryを使用して親divを削除するにはどうすればよいですか?
私のページでは入力を削除できません。 ID remove_field
との新しい要素は、あなたの準備ができて、この関数の実行時間によって存在していなかったので、たまたま
$(document).ready(function() {
var max_fields = 4; //maximum input boxes allowed
//var wrapper = $(".phone-field"); //Fields wrapper
var add_button = $("#add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(){ //on add input button click
if(x < max_fields){ //max input box allowed
$(add_button).
x++; //text box increment
$('.phone-field').append('<div class="col-xs-12 col-md-7 phone-class"><label for="telefones">Telefone</label><div class="input-group"><input type="text" class="form-control" name="telefone[]" placeholder="Digite seu telefone"><span class="input-group-btn"><button class="btn btn-default" id="remove_field" type="button"><i class="fa fa-trash-o" aria-hidden="true"></i></button></span></div></div>'); //add input box
}
});
$("#remove_field").click(function(){ //user click on remove text
//e.preventDefault();
//$('#remove_field').closest('div.phone-class').remove();
$('#remove_field').parent().parent().parent().remove();
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://use.fontawesome.com/1cdb0cfd25.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="form-group phone-field">
<div class="col-xs-12 col-md-7">
<label for="telefones">Telefone</label>
<div class="input-group">
<input type="text" class="form-control" name="telefone[]" placeholder="Digite seu telefone">
<span class="input-group-btn">
<button class="btn btn-default" id="add_field_button" type="button"><i class="fa fa-plus" aria-hidden="true"></i></button>
</span>
</div>
</div>
<div class="col-xs-12 col-md-7 phone-class"> <!-- I want to delete this DIV here if i click on the button with id="remove_field"-->
\t <label for="telefones">Telefone</label>
\t <div class="input-group">
\t \t <input type="text" class="form-control" name="telefone[]" placeholder="Digite seu telefone">
\t \t <span class="input-group-btn"><button class="btn btn-default" id="remove_field" type="button"><i class="fa fa-trash-o" aria-hidden="true"></i></button></span>
\t </div>
</div>
</div>
[動的に作成される要素のイベントバインディングは?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements)また、 'id'属性**は必須です** 一意であること。複数の '#remove_field'要素を持つと、HTMLが無効になります。 –
'id ='の代わりに 'icon = 'remove_field''を使い、スクリプトで '$(this)).parent()。parent()。parent()。remove();'を使用してみてください。 – Vijai
@Vijaiを削除する