How To Remove Dynamically Generated Div Using jQuery - javascript

I want to remove a dynamically generated div using jquery, remove button will be with every div. So when I click any remove button, it will remove that div from DOM.
<div class="form-group" id="drag">
<div class="col-md-2">
<input type="text" class="form-control" id="name1" placeholder="Name">
</div>
<div class="col-md-2">
<input type="text" class="form-control" id="eng1" placeholder="Description Eng">
</div>
<div class="col-md-2">
<input type="text" class="form-control" id="ar1" placeholder="Description Ar">
</div>
<div class="col-md-2">
<a id="remove" href="javascript:;" class="btn btn-sm red">
Remove
<i class="fa fa-close"></i>
</a>
</div>
</div>

If you would generate a div with inside the div a button, you can add the following function to let that button make the parent div disappear:
function removeParent()
{
//remove button click, remove the parent div from the dom
$(this).parent().parent().remove();
//in your specific case you want the parent parent div to be removed since the button is encapsulated by 2 divs.
}
This function you then need to add to the onclick listener of the button. Either by just setting it in the html onclick='removeParent()' or using javascript:
//gerenate div + button
mybutton.addEventListener('click', removeParent, false);

$('body').on('click', '#remove', function(){
$(this).closest('.form-group').remove();
});
But it's not correct to have more than one elements with the same id. recomment you to change ID to class

Try like below. Use class remove instead of id, because id should be unique.
$('body').on('click', '.remove', function(){
$(this).closest('.form-group').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group" id="drag">
<div class="col-md-2">
<input type="text" class="form-control" id="name1" placeholder="Name">
</div>
<div class="col-md-2">
<input type="text" class="form-control" id="eng1" placeholder="Description Eng">
</div>
<div class="col-md-2">
<input type="text" class="form-control" id="ar1" placeholder="Description Ar">
</div>
<div class="col-md-2">
<a class="remove" href="javascript:;" class="btn btn-sm red">
Remove
<i class="fa fa-close"></i>
</a>
</div>
</div>

Related

JavaScript event handler isn't called on appended button

I have form where I can add options and add new fields of options. I am using JQuery for this. The problem is that the remove button of added fields doesn't work.
Here's my form:
Logic
I click Add New button and new row will add Working
I click Remove it has to remove that row Not Working
$(function() {
//add row for options
$("#addnewoptinrow").click(function(e) {
e.preventDefault();
$('.newrow').append('<div class="row mt-3 newrowadded"><div class="col-md-8"><input name="options[]" type="text" class="form-control" placeholder="Option Name"></div><div class="col-md-2"><input name="optionsprices[]" type="number" class="form-control" placeholder="Price"></div><div class="col-md-2"><button type="button" class="removerow btn btn-danger" id="removerow">Remove</button></div></div>');
});
//Remove the row
$('.removerow').on('click', function(e) {
e.preventDefault();
$('.newrowadded').closest("div.row").remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-8">
<input name="options[]" type="text" class="form-control" placeholder="Option Name">
</div>
<div class="col-md-2">
<input name="optionsprices[]" type="number" class="form-control" placeholder="Price">
</div>
<div class="col-md-2">
<button class="addnewqtydiscmsgsave btn btn-primary" id="addnewoptinrow">Add New</button>
</div>
</div>
<div class="newrow"></div>
Any idea how to fix that remove action?
There are two issues in your code:
the call to on() is missing the "selector" argument, which means that no elements dynamically added in future will have the click event boundy
your remove logic needs to be executed relative to the button being clicked
Try the following changes in your .removerow click handler:
/*
Bind the click handler to all elements dynamically added that match the
.removerow selector
*/
$('body').on('click','.removerow', function(e){
e.preventDefault();
/*
Explaination:
1. from "this" remove button being clicked,
2. select the closest ".newrowadded" and,
3. remove it
*/
$(this).closest(".newrowadded").remove();
});
See the snippet below for your a working example based off of your code:
$(function() {
//add row for options
$("#addnewoptinrow").click(function(e) {
e.preventDefault();
$('.newrow').append('<div class="row mt-3 newrowadded"><div class="col-md-8"><input name="options[]" type="text" class="form-control" placeholder="Option Name"></div><div class="col-md-2"><input name="optionsprices[]" type="number" class="form-control" placeholder="Price"></div><div class="col-md-2"><button type="button" class="removerow btn btn-danger">Remove</button></div></div>');
});
//Remove the row
$('body').on('click', '.removerow', function(e) {
e.preventDefault();
$(this).closest(".newrowadded").remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<div class="row">
<div class="col-md-8">
<input name="options[]" type="text" class="form-control" placeholder="Option Name">
</div>
<div class="col-md-2">
<input name="optionsprices[]" type="number" class="form-control" placeholder="Price">
</div>
<div class="col-md-2">
<button class="addnewqtydiscmsgsave btn btn-primary" id="addnewoptinrow">Add New</button>
</div>
</div>
<div class="newrow"></div>
The problem is that your code is only being executed on page load and at this time, your remove button is not yet created. You need to add an event listener to the remove button after your remove button has been created.
Button.removerow was added later. you can try this:
//add row for options
$("#addnewoptinrow").click(function(e) {
e.preventDefault();
$('.newrow').append('<div class="row mt-3 newrowadded"><div class="col-md-8"><input name="options[]" type="text" class="form-control" placeholder="Option Name"></div><div class="col-md-2"><input name="optionsprices[]" type="number" class="form-control" placeholder="Price"></div><div class="col-md-2"><button type="button" class="removerow btn btn-danger" id="removerow">Remove</button></div></div>');
//Remove the row
$('.removerow').on('click', function(e) {
e.preventDefault();
$('.newrowadded').closest("div.row").remove();
});
});
In oder to match your event listener to later created elements, you need to delegate it. In older JQuery versions it was done by the .delegate method, however, in recent versions this method is deprecated. Now you can delegate by ancestorCollection.on('query-selector', 'event', listener).
In your example something like
$('.newrow').on('.removerow', 'click', function(e){ /*...*/ })
The issue is that you are trying to bind actions on elements that are not yet created - you should use a more general binding as below:
$(function(){
//add row for options
$("#addnewoptinrow").click(function(e){
e.preventDefault();
$('.newrow').append('<div class="row mt-3 newrowadded"><div class="col-md-8"><input name="options[]" type="text" class="form-control" placeholder="Option Name"></div><div class="col-md-2"><input name="optionsprices[]" type="number" class="form-control" placeholder="Price"></div><div class="col-md-2"><button type="button" class="removerow btn btn-danger" class="removerow">Remove</button></div></div>');
});
//Remove the row
$(document).on('click','.removerow', function(e){
e.preventDefault();
$(this).parent().parent().remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="row">
<div class="col-md-8">
<input name="options[]" type="text" class="form-control" placeholder="Option Name">
</div>
<div class="col-md-2">
<input name="optionsprices[]" type="number" class="form-control" placeholder="Price">
</div>
<div class="col-md-2">
<button class="addnewqtydiscmsgsave btn btn-primary" id="addnewoptinrow">Add New</button>
</div>
</div>
<div class="newrow"></div>
Pay attention to the
$(document).on('click','.removerow', function(e){
line of code. This line appends the action to all of the '.removerow' elements, present and future. So when new elements are added with this class, they are automatically assigned this action (BTW, had to change your HTML from id="removerow" to class="removerow", to avoid duplicate ID's).
And please read this topic, it goes into more details of your issue.

how to show form in the same page when click button on it

I have a form on the page and displayed it as none. And there is a button in the page I want when clicking on the button the form to display.
How can I do that?
<button type="button" class="btn btn-primary add-city">اضافه مدينة جديدة +</button>
and form code is this
<div id="forma">
<div class="form-head">
<p id="add-city">+اضافة المدينة</p>
<i class="fa fa-times-circle close" aria-hidden="true"></i>
</div>
<form class="">
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>الدولة<span>*</span></label>
<select class="form-control">
<option>اختر الدوله </option>
</select>
</div>
<div class="form-group">
<label>اسم المدينه(عربي)<span>*</span></label>
<input type="text" class="form-control" id="email">
</div>
</div>
<div class="col-md-6">
<div class="form-group ">
<label>المحافظة<span>*</span></label>
<select class="form-control">
<option>اختر المحافظه </option>
</select>
</div>
<div class="form-group">
<label>اسم المدينه(انجليزي)</label>
<input type="text" class="form-control" id="email">
</div>
</div>
</div>
</div>
</form>
<div class="form-footer">
<button type="button" class="btn btn-primary">ارسال</button>
<button type="button" class="btn btn-secondary">الغاء</button>
</div>
</div>
I made a div with an id called forma so that I can call it in javascript. But I don't know the right way.
You can add an onclick attribute to the button that changes the display to block.
onclick="document.getElementById('forma').style.display = 'block'"
Just use the jQuery click property and show property
$( "#idbutton" ).click(function() {
$("#idform").show();
});
If you are using Bootstrap.js, you can safely use jQuery because it's required. Assuming you should click #add-city button to display the form, simply add to your app.js or inside your <script> tags
$('#add-city').click(function() {
$('#forma').show();
});
In order to toggle the form (show/hide) on every click, you could do something like
$('#add-city').click(function() {
$('#forma').toggleClass('hidden');
});

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
}

jQuery .on() issue, console.log() works but element interaction doesn't

I am using this code inside $(document).ready(function(){ ... }):
$('#flavours').on('click', '.toggle-quantity', function(e){
e.preventDefault();
var $quantity_percent = $(this).parent().find('.quantity_percent');
if($quantity_percent.is(':hidden')){
console.log("is hidden");
$quantity_percent.show();
}else{
console.log("is not hidden");
$quantity_percent.hide();
}
});
What's happening is the console.log() is working, but the $quantity_percent is not showing/hiding.
Additionally, if I add an alert('test') to the beginning of the function (just after e.preventDefault) this also doesn't work, but the console.log() continues to work (it correctly logs 'is not hidden').
EDIT: Relevant HTML markup:
<div id="flavours">
<div class="row flavour" id="flavour_1" style="display: block;">
<div class="form-group">
<div class="col-xs-12">
<fieldset>
<legend>Flavour 1</legend>
<div class="col-sm-4">
<label>Flavour Name</label>
<input type="text" value="" name="flavour_name[]" data-flavour-id="1" id="flavour_name_1" class="form-control autocomp" placeholder="Flavour name">
<input type="hidden" value="" name="flavour_id[]" id="flavour_id_1" class="form-control flavour_id">
<p class="flavour_info"></p>
</div>
<div class="col-sm-6">
<label>Flavour Quantity <span class="fa fa-filter"></span> <span class="hidden-sm">Switch to </span>drops per ml</label>
<div class="input-group" id="quantity_percent">
<input type="text" class="form-control" id="flavour_percentage_1" name="flavour_percentage[]" placeholder="Flavour Quantity">
<span class="input-group-addon">%</span>
</div>
<div class="input-group" id="quantity_drops" style="display: none;">
<input type="text" class="form-control" id="flavour_drops_1" name="flavour_drops[]" placeholder="Flavour Quantity">
<span class="input-group-addon">drops/ml</span>
</div>
<p class="flavour_recommended_percentage"></p>
</div>
<div class="col-sm-2">
<label> </label>
<button class="btn btn-danger btn-block remove-flavour"><span class="glyphicon glyphicon-remove"></span> Remove</button>
</div>
</fieldset>
</div>
</div>
</div>
$(this).parent() is a label element which doesn't have a child with .quantity_percent
Also quantity_percent is an id and not a class. Use the ID selector
So use
var $quantity_percent = $('#quantity_percent');
instead of
var $quantity_percent = $(this).parent().find('.quantity_percent');
Note: IDs must be unique in HTML
EDIT: as per OPs comments
I updated it to a class rather than ID (as it's on a dynamically growing list)
Usage
var $quantity_percent = $(this).closest('.col-sm-6').find('.quantity_percent');
The .parent() targets the <label> therefore it can't find .quantity_percent

Categories

Resources