How can I remove a parent div using jquery? - javascript

I want to remove the first div and everything else inside.
Here in the code snippet I can delete the first input, but I cant delete the others if I add more.
On my page I can't delete any input.
$(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"-->
<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>
</div>

That happens because the new elements with id remove_field didn't existed by the time your ready function ran. This way the only elements bonded to the function that removes the field is the one that already is on the DOM element.
Luckily for you that's a pretty common mistake and a fair simple one to solve also. You just need to bind an permanent parent element using jQuery's .on function:
$(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
}
});
$(".phone-field").on('click','#remove_field',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"-->
<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>
</div>

1) When you are inside a listener use "this" to refer to the object
2) Use closest instead of parent().parent().parent() or your function will be useless if HTML changes:
3) Make "remove_field" a class, as you have multiple elements with the same id, and as previous comment stated that is not valid HTML
$(this).closest('div.phone-class').remove();

Related

How to create dynamic element in a dynamic form

this is my code for first element, inside of first dynamic form
<input type="text" class=" form-control" id="pPilihan" style="font-size: 1rem;" name="p_pilihan[]" required placeholder="Masukan Nama Pilihan, contoh: Merah / XL">
Tambah
this is my code for add input element
<div class="copy d-none">
<div class="control-group input-group" style="margin-top:10px">
<input type="text" class="form-control" id="pPilihan" style="font-size: 1rem;" name="p_pilihan[]" required placeholder="Masukan Nama Pilihan, contoh: Merah / XL">
<div class="input-group-btn">
<button class="btn btn-danger remove" type="button"><i class="glyphicon glyphicon-remove"></i> Hapus</button>
</div>
</div>
</div>
and this is my js
$(document).ready(function() {
$("body").on("click", ".add-more", function(){
var html = $(".copy").html();
$(".after-add-more").before(html);
});
$("body").on("click",".remove",function(){
$(this).parents(".control-group").remove();
});
});
The question is not clear to me but I can see a bug in your code, you simply can't have two elements having the same id. Each time 'add more' button is clicked the input element with id="pPilihan" is getting repeated, which is wrong. You can solve this by using a counter to produce a dynamic id (if you need one).

How to clear text id in javascript

I have a one text box search, and one button,when i add the text and click button, related data will be getting but when i click another search.that is taking same id,previous id not clearing. how to clear that id
<div class="col-lg-4 col-sm-4 col-xs-12">
<i class="glyphicon glyphicon-search"></i>
<div class="form-group">
<input type="text" class="form-control" id="isbncollegeid" data-ng-model="isbncollege" placeholder=" Search By college ISBN" name="isbncollegeid">
</div>
</div>
<div class="col-sm-4">
<br />
<div class="form-group">
<input type="hidden" id="bookcollgeIsbn" name="bookcollgeIsbn" />
<button type="button" class="btn btn-sky" id="IsbntcolDetails" data-ng-disabled="LibraryIsbnForm.$invalid" data-ng-click="DetailscolByISBN()">Get Details<i class="fa fa-exclamation"></i>
</button>
<button type="button" class="btn btn-sky" id="clear" data-ng-click="ClearISbnCollege()">Clear<i class="fa fa-exclamation"></i>
</button>
</div>
</div>
In your ClearISbnCollege just make isbncollege model empty
$scope.ClearISbnCollege = function() {
$scope.isbncollege = "";
}
When you will click the Clear button, input will be emptied.
You can use below line of code after getting results in javascript:
document.getElementById('elementid').value = "";
in Jquery:
$('#elementid').val("");

UPDATE Collection of data with array of inputs

I have 3 inputs in my form. residence[], mobile[], office[]. I also have buttons for each inputs that will append them when clicked. So far, I managed to insert 3 values for each input into my database. But how can I Update all of them ? This is my controller for update
public function postEdit(ReservedEditRequest $reserved_edit_request, $id) {
foreach (Input::get('residence','mobile','office') as $key => $val) {
$student_contacts = StudentContacts::where('student_contacts.student_id',$id)
->update([
'residence' => Input::get("residence.$key"),
'mobile' => Input::get("mobile.$key"),
'office' => Input::get("office.$key"),
]);
}
return redirect('registrar/register_student')->withErrors('mobile')->with('message', 'Student Details Successfully Modified');
}
the code above will retrieve a collection
residence----------------------mobile-----------------------office
VAL1----------------------------VAL1------------------------VAL1
VAL2----------------------------VAL2------------------------VAL2
VAL3----------------------------VAL3------------------------VAL3
and when i submit the form, it saves the 3rd VALUE for all fields making it
residence----------------------mobile-----------------------office
VAL3----------------------------VAL3------------------------VAL3
VAL3----------------------------VAL3------------------------VAL3
VAL3----------------------------VAL3------------------------VAL3
Any answer will be appreciated :) Thanks
EDITED
this is the form
<div class="col-xs-1">
<button type="button" id="add_field_button_residence" class="btn btn-sm btn-primary" pull-right>
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
<div class="col-sm-3">
<div class="input_fields_wrap_residence">
#if($action == 1)
#foreach($student_contacts as $contacts)
<input type="text" name="residence[]" id="residence[]" class="form-control" pattern="[\(]\d{2}[\)]\d{7}" placeholder="Residence e.g. (32)1234567" value="{{{$contacts -> residence}}}"/>
<span class="help-block">{!!$errors->first('residence', '<span class="help-block">:message </span>')!!}</span>
#endforeach
#else
<input type="text" name="residence[]" id="residence[]" class="form-control" pattern="[\(]\d{2}[\)]\d{7}" placeholder="Residence e.g. (32)1234567" value="{{{Input::old('residence', isset($student_contacts) ? $student_contacts_residence : null )}}}"/>
<span class="help-block">{!!$errors->first('residence', '<span class="help-block">:message </span>')!!}</span>
#endif
</div>
</div>
<div class="col-xs-1">
<button type="button" id="add_field_button_mobile" class="btn btn-sm btn-primary" pull-right>
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
<div class="col-sm-3">
<div class="input_fields_wrap_mobile">
#if($action == 1)
#foreach($student_contacts as $contacts)
<input type="text" name="mobile[]" id="mobile[]" class="form-control" pattern="(09)[0-9]{9}" placeholder="Mobile Phone" value="{{{$contacts -> mobile}}}" required/>
<span class="help-block">{!!$errors->first('mobile', '<span class="help-block">:message </span>')!!}</span>
#endforeach
#else
<input type="text" name="mobile[]" id="mobile[]" class="form-control" pattern="(09)[0-9]{9}" placeholder="Mobile Phone" value="{{{Input::old('mobile', isset($student_contacts) ? $student_contacts_mobile : null)}}}" required/>
<span class="help-block">{!!$errors->first('mobile', '<span class="help-block">:message </span>')!!}</span>
#endif
</div>
</div>
<div class="col-xs-1">
<button type="button" id="add_field_button_office" class="btn btn-sm btn-primary" pull-right>
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
<div class="col-sm-3">
<div class="input_fields_wrap_office">
#if($action == 1)
#foreach($student_contacts as $contacts)
<input type="text" name="office[]" id="office[]" class="form-control" pattern="[\(]\d{2}[\)]\d{7}" placeholder="Office e.g. (32)1234567" value="{{{$contacts->office}}}"/>
<span class="help-block">{!!$errors->first('office', '<span class="help-block">:message </span>')!!}</span>
#endforeach
#else
<input type="text" name="office[]" id="office[]" class="form-control" pattern="[\(]\d{2}[\)]\d{7}" placeholder="Office e.g. (32)1234567" value="{{{Input::old('office', isset($student_contacts) ? $student_contacts_office : null )}}}"/>
<span class="help-block">{!!$errors->first('office', '<span class="help-block">:message </span>')!!}</span>
#endif
</div>
</div>
the button will append the inputs through javascript . Here is the code
$(document).ready(function() {
var max_fields = 3; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap_mobile"); //Fields wrapper
var add_button = $("#add_field_button_mobile"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mobile[]" id="mobile[]" class="form-control" pattern="(09)[0-9]{9}" placeholder="Mobile Phone" value="{{{Input::old('mobile', isset($student_contacts) ? $student_contacts_mobile : null)}}}" required/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field_mobile", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
same code is applied to others

How to delete total div content using Javascript/Jquery

I need to delete the last textarea in a div.
<div id="container">
<!-- question 1st box starts here -->
<div class="col-md-4">
<div class="questionparts">
<div class="form-group">
<label for="title">Questions</label>
<textarea class="form-control" name="questions0" id="questions0" placeholder="Questions" style="background:#FFFFFF;" rows="2"></textarea>
</div>
<div class="clear"></div>
<div class="questionshowp">
<h4 class="page-title">Multiple Choice</h4>
<h6>Your audience can select from these answers:</h6>
<div class="form-group">
<input name="questions1" id="questions1" class="form-control firstsec" placeholder="Text, Image URL, or LaTeX" value="" type="text">
<div class="secondsec">
<button type="button" class="btn btn-sm btn-success" style="line-height:12px;"><i class="fa fa-plus" aria-hidden="true"></i></button>
<button type="button" class="btn btn-sm btn-danger" style="line-height:12px;"><i class="fa fa-minus" aria-hidden="true"></i></button>
</div>
</div>
<div class="clear"></div>
</div>
</div>
</div>
<!-- question 1st box end here -->
<!-- question 2nd box starts here -->
<div class="col-md-4">
<div class="questionparts">
<div class="form-group">
<label for="title">Questions</label>
<textarea class="form-control" name="questions0" id="questions0" placeholder="Questions" style="background:#FFFFFF;" rows="2"></textarea>
</div>
<div class="clear"></div>
<div class="questionshowp">
<h4 class="page-title">Multiple Choice</h4>
<h6>Your audience can select from these answers:</h6>
<div class="form-group">
<input name="questions1" id="questions1" class="form-control firstsec" placeholder="Text, Image URL, or LaTeX" value="" type="text">
<div class="secondsec">
<button type="button" class="btn btn-sm btn-success" style="line-height:12px;"><i class="fa fa-plus" aria-hidden="true"></i></button>
<button type="button" class="btn btn-sm btn-danger" style="line-height:12px;"><i class="fa fa-minus" aria-hidden="true"></i></button>
</div>
</div>
<div class="clear"></div>
</div>
</div>
</div>
<!-- question 2nd box end here -->
</div>
Here I need to delete the last textarea ('in this case 2nd box') always. Check javascript below.
function deleteQuestionField(){
var textareas = $('#container textarea');
console.log('hii',textareas);
if (textareas.length !== 0) {
textareas.last().remove();
}
}
This function is called from a button click event but its not deleting the last textarea.
Simply use jQuery's .remove() (see here for more info):
Give your div that you want to remove a unique id and then call it:
HTML:
....
<!-- question 2nd box starts here -->
<div class="col-md-4" id="someUniqueId">
....
Javascript:
function deleteQuestionField(){
var textareas = $('#container textarea');
console.log('hii',textareas);
if (textareas.length !== 0) {
$("#someUniqueId").remove(); //This will remove the unique id element
}
}
You have the html() function in jQuery
http://api.jquery.com/html/ to remove all codes between an element
The remove() function you used delete the selected element
If you want to delete the content of the textarea, try to use the val() function instead.http://api.jquery.com/val/
$('textarea').val('');
If I understand it correctly if the first textarea is not empty you want to remove the second 'box' . If this is the case you should select the first textarea and not textarea in general (I assume)
firstly add an ID to the second div <div class="col-md-4" id="remove_this"> and call the ID in the remove function
So probably it would be something like:
function deleteQuestionField(){
var textareas = $('#questions0'); //if you want general just use textarea ( `$('#container textarea');`)
console.log('hii',textareas);
if (textareas.length !== 0) {
$("#remove_this").remove();
}
}
Documentation about the .remove function HERE
You want to delete total div ,but you are making delete only textarea element
textareas.last().remove();
//change above code to like below ,it will delete the whole div
$(".col-md-4").last().remove();
With Jquery
$("#item_id").empty();
It works

want to reset only the last newly inserted dynamically block on the click of button

var qBlock='<form id="resetblock"><div class="newqandaBlock"><div class="input-group margin-bottom-20"><span class="input-group-addon purple"><i class="fa fa-question"></i></span><input type="text" class="form-control" placeholder="Question Asked "><button type="button" class="btn btn-purple closequest" style="position: absolute;top: 3px;"><span> <i class="fa fa-close"></i></span></button></div> <div class="input-group margin-bottom-20"> <span class="input-group-addon purple"><i class="fa fa-reply"></i></span><textarea rows="3" class="form-control" name="info" placeholder="Your Answer"></textarea> </div><div class="input-group margin-bottom-20"><span class="input-group-addon purple"><i class="fa fa-comments"></i></span><textarea rows="3" class="form-control" name="info" placeholder="Add Your Comments"></textarea> </div></div></form>';
$("#addQuestion").on("click",function(){
$(qBlock).insertAfter(".qandaBlock");
});
$("#resetblock").on("click",'.closequest', function(){
alert("Do you really want to remove the question?!?");
$(this).closest(".newqandaBlock").remove();
});
$("#resetblock").on("click",'.resetlatest', function(){
alert("Do you really want to reset the question?!?");
$(this).closest('form').find("input[type=text], textarea").val("");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<form id="resetblock" name="resetblock" >
<div class="qandaBlock">
<div class="input-group margin-bottom-20">
<span class="input-group-addon purple"><i class="fa fa-question"></i></span>
<input type="text" class="form-control" placeholder="Question Asked ">
</div>
<div class="input-group margin-bottom-20">
<span class="input-group-addon purple"><i class="fa fa-reply"></i></span>
<textarea rows="3" class="form-control" name="info" placeholder="Your Answer"></textarea>
</div>
<div class="input-group margin-bottom-20">
<span class="input-group-addon purple"><i class="fa fa-comments"></i></span>
<textarea rows="3" class="form-control" name="info" placeholder="Add Your Comments"></textarea> </div>
</div>
<button type="button" class="btn btn-default resetlatest" id="resetlatest" ">Reset</button>
<button type="button" class="btn btn-purple" id="addQuestion"><i class="fa fa-plus-square-o"></i> Add Another Question</button>
</div>
</form>
</body>
</html>
The above line of code will reset the whole form. But , How to reset only the last newly inserted block of question , answer and comment. I dont want on the click of the reset button, the whole form to be reset. I only want to reset the last newly inserted block to be clear its fields with blanks on the click of reset button.
something like this: http://jsfiddle.net/swm53ran/25/
to achieve getting the last or newly inserted element, i used jquery's :last-child selector as seen below.
its also better (and more maintainable) to use .clone() than it is to build html with javascript if you have a template.
<div class="content">
<div id="template" class="section">
<input class="question" type="text" />
<br/>
<textarea class="answer"></textarea>
<br/>
<textarea class="comments"></textarea>
</div>
</div>
<br/>
<br/>
Reset Last Question
Add Another Question
$('.add').on('click', function() {
var clone = $('#template').clone(true).attr('id', '');
clone.find('.question').val('');
clone.find('.answer').val('');
clone.find('.comments').val('');
clone.appendTo('.content');
});
$('.reset').on('click', function() {
console.log($('.section').length);
var last = $('.content .section:last-child');
last.find('.question').val('');
last.find('.answer').val('');
last.find('.comments').val('');
});
A few things to change, other than the sh**ty markup:
1) Stop the forms from nesting each other and put the new form at the bottom after other forms:
$("#addQuestion").on("click",function(){
$(qBlock).insertAfter(".qandaBlock");
});
to
$("#addQuestion").on("click",function(){
$('body').append(qBlock); // Append the form to the body, so it will sit after the last form
});
2) Remove all id="resetblock", from markup and from the JS
3) Change all $("#resetblock").on("click" to $(document).on("click"
4) Change the alert's to confirm's:
var blnReset = confirm("Do you want to reset the question?");
if (blnReset == true) {
//Reset the question
}

Categories

Resources