I have code that clones/adds a div element and it's children when a button is clicked, however, when the remove button is clicked, it doesn't seem to be removing the closest div to the remove button. Can you help with this.
$(function() {
//on click
$(".btn-primary").on("click", function() {
//alert($(".input-group").length)
var
//get length of selections
length = $(".input-group").length,
//create new id
newId = "selection-" + length,
//clone first element with new id
clone = $("#selection").clone().attr("id", newId);
clone.children('.show-tick').attr('id', 'select-' + length++);
//append clone on the end
$("#selections").append(clone);
});
$(".btn-secondary").on("click", function() {
$(this).closest('.input-group').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selections">
<div class="input-group" id="selection">
<span class="input-group-addon">
<i class="icon wb-menu" aria-hidden="true"></i>
</span>
<select class="show-tick" data-plugin="select2" id="select">
<option>True</option>
<option>False</option>
</select>
</div>
</div>
<button class="btn btn-primary" type="button" style="margin-left:30px;">Add new selection</button>
<button class="btn btn-secondary" type="button" style="margin-left:30px;">Remove new selection</button>
To remove last select item you should use:
$("#selections").find('select').last().remove();
In your function:
$(".btn-secondary").on("click", function() {
$("#selections").find('select').last().remove();
});
or do just
$('#selections div:last').remove();
You can use :last-child selector:
$('.input-group:last-child').remove();
Use the last method $("#selections").children("div").last().remove();
$(function() {
//on click
$(".btn-primary").on("click", function() {
//alert($(".input-group").length)
var
//get length of selections
length = $(".input-group").length,
//create new id
newId = "selection-" + length,
//clone first element with new id
clone = $("#selection").clone().attr("id", newId);
clone.children('.show-tick').attr('id', 'select-' + length++);
//append clone on the end
$("#selections").append(clone);
});
$(".btn-secondary").on("click", function() {
$("#selections").children("div").last().remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selections">
<div class="input-group" id="selection">
<span class="input-group-addon">
<i class="icon wb-menu" aria-hidden="true"></i>
</span>
<select class="show-tick" data-plugin="select2" id="select">
<option>True</option>
<option>False</option>
</select>
</div>
</div>
<button class="btn btn-primary" type="button" style="margin-left:30px;">Add new selection</button>
<button class="btn btn-secondary" type="button" style="margin-left:30px;">Remove new selection</button>
There is various way you can do inside your click handler:
$("#selections .input-group:last-child").remove();
// Or
$(".input-group:last-child", "#selections").remove();
// Or
$(".input-group", "#selections").last().remove();
Using the first way:
$(function() {
//on click
$(".btn-primary").on("click", function() {
//alert($(".input-group").length)
var
//get length of selections
length = $(".input-group").length,
//create new id
newId = "selection-" + length,
//clone first element with new id
clone = $("#selection").clone().attr("id", newId);
clone.children('.show-tick').attr('id', 'select-' + length++);
//append clone on the end
$("#selections").append(clone);
});
$(".btn-secondary").on("click", function() {
$("#selections .input-group:last-child").remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selections">
<div class="input-group" id="selection">
<span class="input-group-addon">
<i class="icon wb-menu" aria-hidden="true"></i>
</span>
<select class="show-tick" data-plugin="select2" id="select">
<option>True</option>
<option>False</option>
</select>
</div>
</div>
<button class="btn btn-primary" type="button" style="margin-left:30px;">Add new selection</button>
<button class="btn btn-secondary" type="button" style="margin-left:30px;">Remove new selection</button>
You should also add a check that, there is at least 1 .input-group element left for add button to work, because if there is no .input-group element, which element you'll clone? So, add a check like:
$(function() {
//on click
$(".btn-primary").on("click", function() {
//alert($(".input-group").length)
var
//get length of selections
length = $(".input-group").length,
//create new id
newId = "selection-" + length,
//clone first element with new id
clone = $("#selection").clone().attr("id", newId);
clone.children('.show-tick').attr('id', 'select-' + length++);
//append clone on the end
$("#selections").append(clone);
});
$(".btn-secondary").on("click", function() {
var length = $(".input-group").length;
if (length === 1) {
alert("Can not delete the last element");
return;
}
$("#selections .input-group:last-child").remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selections">
<div class="input-group" id="selection">
<span class="input-group-addon">
<i class="icon wb-menu" aria-hidden="true"></i>
</span>
<select class="show-tick" data-plugin="select2" id="select">
<option>True</option>
<option>False</option>
</select>
</div>
</div>
<button class="btn btn-primary" type="button" style="margin-left:30px;">Add new selection</button>
<button class="btn btn-secondary" type="button" style="margin-left:30px;">Remove new selection</button>
You want the last .input-group so replace the last line with this:
$('.input-group').last().remove();
The buttons are actually siblings of #selections so the point of reference (this) doesn't need to be from the button itself. .closest() would target ancestor elements of the button and the .input-group is more like a "nephew/niece" relation to the buttons. Using the parent container #selections or the collection of .input-group is sufficient.
Edit
Added a condition that should the $('.input-group').length be 1, that it be spared from being deleted, otherwise, there'd be nothing to clone.
Demo
$(function() {
//on click
$(".btn-primary").on("click", function() {
//alert($(".input-group").length)
var
//get length of selections
length = $(".input-group").length,
//create new id
newId = "selection-" + length,
//clone first element with new id
clone = $("#selection").clone(true, true).attr("id", newId);
clone.find('.show-tick').attr('id', 'select-' + length++);
//append clone on the end
$("#selections").append(clone);
});
$(".btn-secondary").on("click", function() {
if ($(".input-group").length > 1) {
$('.input-group').last().remove();
} else {
return false;
}
});
});
<div id="selections">
<div class="input-group" id="selection">
<span class="input-group-addon">
<i class="icon wb-menu" aria-hidden="true"></i>
</span>
<select class="show-tick" data-plugin="select2" id="select">
<option>True</option>
<option>False</option>
</select>
</div>
</div>
<button class="btn btn-primary" type="button" style="margin-left:
30px;">
Add new selection
</button>
<button class="btn btn-secondary" type="button" style="margin-left:
30px;">
Remove new selection
</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Related
I am creating a HTML form for data entry that contains a couple of textboxes and function buttons.
There is also an add button that copies (clones) from a DIV template (id: w) for each "row" and appends to the end of the main DIV (id: t). On each row, there is a "X" button to remove the row and two arrow buttons to visually move the "row" up and down in the DOM.
The form is dynamically created from a database and the elements already on the page when the page is loaded and using jQuery 3.4.1, for the selecting and most of the DOM manipulation using the functionality of each rows buttons.
The "rows" are added to the container DIV and the elements are renamed depending on the counter which is expected. The "X" button deletes the "row", and moves all pre-existing rows up and down in the container DIV.
But for some unknown reason any new rows that are created I have to press the "up" button twice. The "down" button for the bottom row, is redundant and not functional.
I think it might have to do with the previousSibling and nextSibling returning the wrong Object type and causing a problem and failing the first time.
Any thoughts on how to fix or improve this functionality?
var rr = $("[id^=l]").length;
$(".data-up").click(function() {
var e = $(this).first().parent().parent().get(0);
moveUp(e);
});
$(".data-down").click(function() {
var e = $(this).parent().parent().get(0);
moveDown(e);
});
$(".remove").click(function() {
$(this).parent().parent().remove();
});
function add() {
rr += 1;
var a = $("#w").clone(true, true).removeAttr('id').removeAttr('style');
a.attr("datarow", "row" + rw);
a.find("input[data-field='l']").attr("id", "l" + rr).attr("name", "l" + rr).removeAttr("data-field");
a.find("input[data-field='s']").attr("id", "s" + rr).attr("name", "s" + rr).removeAttr("data-field");
a.appendTo("#t");
}
function moveUp(e) {
if (e.previousSibling) {
if (e.previousSibling === e.parentNode.children[0]) {} else {
e.parentNode.insertBefore(e, e.previousSibling);
}
}
}
function moveDown(e) {
if (e === e.parentNode.children[e.parentNode.children.length - 1]) {} else {
e.parentNode.insertBefore(e.nextSibling, e);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button type="button" class="btn btn-secondary" ID="p" onclick="add();">Add</button>
<div id="t">
</div>
<div class="form-group row" id="w" style="display:none;" datarow="row">
<div class="col-sm-1"><input name="s" class="form-control txt-s col-form-label" id="s" type="text" readonly="true" data-field="s"></div>
<div class="col-sm-3"><input name="l" class="form-control txt-l" id="l" type="text" data-field="l"></div>
<div class="col-sm-2">
<button class="btn btn-danger mr-1 remove" type="button">X</button>
<button class="btn btn-info mr-1 data-up" type="button">↑</button>
<button class="btn btn-info data-down" type="button">↓</button>
</div>
</div>
With jQuery - use .closest() to find the current parent of the button. The find the .prev() or the .next() sibling. If the sibling exists use .insertBefore() or .insertAfter() to move the current parent before or after the sibling:
var rr = $("[id^=l]").length;
$(".data-up").click(function(e) {
var current = $(this).closest('.form-group'); // find the current parent
var target = current.prev(); // find the relevant sibling
if(target.length) { // if sibling exists
current.insertBefore(target); // insert the current item above it
}
});
$(".data-down").click(function() {
var current = $(this).closest('.form-group'); // find the current parent
var target = current.next(); // find the next sibling
if(target.length) { // if the next sibling exists
current.insertAfter(target); // insert the current item after it
}
});
$(".remove").click(function() {
$(this).parent().parent().remove();
});
function add() {
rr += 1;
var a = $("#w").clone(true, true).removeAttr('id').removeAttr('style');
a.attr("datarow", "row" + rr);
a.find("input[data-field='l']").attr("id", "l" + rr).attr("name", "l" + rr).removeAttr("data-field");
a.find("input[data-field='s']").attr("id", "s" + rr).attr("name", "s" + rr).removeAttr("data-field");
a.appendTo("#t");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button type="button" class="btn btn-secondary" ID="p" onclick="add();">Add</button>
<div id="t">
</div>
<div class="form-group row" id="w" style="display:none;" datarow="row">
<div class="col-sm-1"><input name="s" class="form-control txt-s col-form-label" id="s" type="text" readonly="true" data-field="s"></div>
<div class="col-sm-3"><input name="l" class="form-control txt-l" id="l" type="text" data-field="l"></div>
<div class="col-sm-2">
<button class="btn btn-danger mr-1 remove" type="button">X</button>
<button class="btn btn-info mr-1 data-up" type="button">↑</button>
<button class="btn btn-info data-down" type="button">↓</button>
</div>
</div>
What's wrong in your code
The problem with the up button is e.previousSibling === e.parentNode.children[0] - the 1st element is always the first item in the collection, so this blocks you from moving an item above it. All you have to check is if there is a previousSibling for up, and nextSibling for down.
Fixed code + comments:
var rr = $("[id^=l]").length;
$(".data-up").click(function() {
var e = $(this).parent().parent().get(0); // first() is redundant - this is the only element in the collection
moveUp(e);
});
$(".data-down").click(function() {
var e = $(this).parent().parent().get(0);
moveDown(e);
});
$(".remove").click(function() {
$(this).parent().parent().remove();
});
function add() {
rr += 1;
var a = $("#w").clone(true, true).removeAttr('id').removeAttr('style');
a.attr("datarow", "row" + rr);
a.find("input[data-field='l']").attr("id", "l" + rr).attr("name", "l" + rr).removeAttr("data-field");
a.find("input[data-field='s']").attr("id", "s" + rr).attr("name", "s" + rr).removeAttr("data-field");
a.appendTo("#t");
}
function moveUp(e) {
if (e.previousSibling) { // just check if there's a previous sibling
e.parentNode.insertBefore(e, e.previousSibling);
}
}
function moveDown(e) {
if (e.nextSibling) { // just check if there's a next sibling
e.parentNode.insertBefore(e.nextSibling, e);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button type="button" class="btn btn-secondary" ID="p" onclick="add();">Add</button>
<div id="t">
</div>
<div class="form-group row" id="w" style="display:none;" datarow="row">
<div class="col-sm-1"><input name="s" class="form-control txt-s col-form-label" id="s" type="text" readonly="true" data-field="s"></div>
<div class="col-sm-3"><input name="l" class="form-control txt-l" id="l" type="text" data-field="l"></div>
<div class="col-sm-2">
<button class="btn btn-danger mr-1 remove" type="button">X</button>
<button class="btn btn-info mr-1 data-up" type="button">↑</button>
<button class="btn btn-info data-down" type="button">↓</button>
</div>
</div>
I have a dual list in which you get an option to add left list item in right list. And right list is a form. Now i am stuck at a problem where when user click the submit button all the li in right list and there inside values get store in an object with there specific name div id name. I have worked on it for 5 days now but unable to collect data according to div id name. Like
<div id="name1">
<input id="tts" type="text" value="${CTLIST.tts}"> s<br>
<input id="topic_level" type="text" value="${CTLIST.topic_level}"><br>
<label>${Object.keys(CTLIST)[4]}</label> <input id="to_be_shown_individually" type="checkbox" ${(CTLIST.to_be_shown_individually && 'checked')}> <br>
<label>${Object.keys(CTLIST)[3]}</label><input id="check_for_geometry" type="checkbox" ${(CTLIST.check_for_geometry && 'checked')}><br>
</div>
Suppose this is an li of right list.
I want data to get stored like
{
[name : name1,
tts.value : 10,
ifcheckboxcheck : true,
],
[name : name2,
tts.value : 10,
ifcheckboxcheck : true,]
}
HEre is my html
<section class="ctList">
<div class="container">
<div class="row">
<div class="dual-list list-left col-md-5">
<div class="well text-right">
<div class="row">
<div class="col-md-10">
<div class="input-group">
<span class="input-group-addon glyphicon glyphicon-search"><i class="fa fa-search"
aria-hidden="true" style="padding-right: 20px;"></i></span>
<input type="text" name="SearchDualList" class="form-control"
placeholder="search" />
</div>
</div>
<div class="col-md-2">
<div class="btn-group">
<a class="btn btn-default selector" title="select all"><i
class="glyphicon glyphicon-unchecked"></i></a>
</div>
</div>
</div>
<ul class="list-group" id="La">
</ul>
</div>
</div>
<div class="list-arrows col-md-1 text-center">
<button class="btn btn-default btn-sm move-left">
<span class="glyphicon glyphicon-chevron-left"><i class="fa fa-arrow-left"
aria-hidden="true"></i></span>
</button>
<button class="btn btn-default btn-sm move-right">
<span class="glyphicon glyphicon-chevron-right"><i class="fa fa-arrow-right"
aria-hidden="true"></i></span>
</button>
</div>
<div class="dual-list list-right col-md-5">
<div class="well">
<div class="row">
<div class="col-md-2">
<div class="btn-group">
<a class="btn btn-default selector" title="select all"><i
class="glyphicon glyphicon-unchecked"></i></a>
</div>
</div>
<div class="col-md-10">
<div class="input-group">
<input type="text" name="SearchDualList" class="form-control"
placeholder="search" />
<span class="input-group-addon glyphicon glyphicon-search"></span>
</div>
</div>
</div>
<form id="rightData" method="POST">
<ul class="list-group" id="accordian">
<!-- right list -->
</ul>
<input type="submit" value="submit" name="submit">
</form>
</div>
</div>
</div>
</div>
</section>
This is my js which is obviously not working
$('.content').hide();
$('.listelement').on('click', function () {
if (!($(this).children('.content').is(':visible'))) {
$('.content').slideUp();
$(this).children('.content').slideDown();
} else {
$('.content').slideUp();
}
});
$(function () {
$('body').on('click', '.list-group .list-group-item', function () {
$(this).toggleClass('active');
});
$('.list-arrows button').click(function () {
var $button = $(this), actives = '';
if ($button.hasClass('move-left')) {
actives = $('.list-right ul li.active');
actives.clone().appendTo('.list-left ul');
actives.remove();
} else if ($button.hasClass('move-right')) {
actives = $('.list-left ul li.active');
actives.clone().appendTo('.list-right ul');
actives.remove();
}
});
$('.dual-list .selector').click(function () {
var $checkBox = $(this);
if (!$checkBox.hasClass('selected')) {
$checkBox.addClass('selected').closest('.well').find('ul li:not(.active)').addClass('active right');
$checkBox.children('i').removeClass('glyphicon-unchecked').addClass('glyphicon-check');
} else {
$checkBox.removeClass('selected').closest('.well').find('ul li.active').removeClass('active');
$checkBox.children('i').removeClass('glyphicon-check').addClass('glyphicon-unchecked');
}
});
$('[name="SearchDualList"]').keyup(function (e) {
var code = e.keyCode || e.which;
if (code == '9') return;
if (code == '27') $(this).val(null);
var $rows = $(this).closest('.dual-list').find('.list-group li');
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function () {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
});
////printing properties
$(function () {
var ctList = [];
var ctRight = [];
var $tBody = $("#La");
var $rbody = $("#accordian");
$.getJSON('https://api.myjson.com/bins/d6n2a', function (data) {
data.topic_info.qt_ct_connection.map(value => {
value.ct_list.forEach((CTLIST) => {
$tBody.append(`<li class="list-group-item" id="rl">
<span id="nameOfCt">${CTLIST.ct}</span>
View More
<div id="${CTLIST.ct}" class="collapse valueDiv">
<label>${Object.keys(CTLIST)[2]}</label> <input id="tts" type="text" value="${CTLIST.tts}"><br>
<label>${Object.keys(CTLIST)[1]}</label> <input id="topic_level" type="text" value="${CTLIST.topic_level}"><br>
<label>${Object.keys(CTLIST)[4]}</label> <input id="to_be_shown_individually" type="checkbox" ${(CTLIST.to_be_shown_individually && 'checked')}> <br>
<label>${Object.keys(CTLIST)[3]}</label><input id="check_for_geometry" type="checkbox" ${(CTLIST.check_for_geometry && 'checked')}><br>
</div>
</li>`);
});
})
})
})
</script>
<script>
var SendDataObject = {};
$("#rightData").on("submit", function (event) {
event.preventDefault();
var IDs = [];
var list = {};
var data = {} ;
var tts = {};
let rightListLength;
rightListLength = $('#rightData li').length;
var tts = [];
$("#rightData li").each(function (){
$("#rightdata").find("div").each(function(){ IDs.push(this.id);
$('#rightData').find("#tts").each(function () { IDs.push(this.value)})
})
});
// $('#rightData li').each(function () {
// var a = $(this).html();
// console.log("i am writin second", list[$(this).attr('value')] = $(this).html());
// console.log(list[$(this).attr('id')] = $(this).html())
// });
console.log(IDs)
console.log(tts)
CSS
<style>
.ctList {
padding-top: 20px;
}
.ctList .dual-list .list-group {
margin-top: 8px;
}
.ctList .list-left li,
.list-right li {
cursor: pointer;
}
.ctList .list-arrows {
padding-top: 100px;
}
.ctList .list-arrows button {
margin-bottom: 20px;
}
.dual-list.list-left .well li.list-group-item .show {
display: none;
}
</style>
This is rendered HTML in browser if ony one li in right list . ANd if two li then another HTML will be rendered by diffrent i name coming from json and value .
point_in_first_quad
View More
<div id="point_in_first_quad" class="collapse valueDiv">
<label>tts</label> <input id="tts" type="text" value="10"><br>
<label>topic_level</label> <input id="topic_level" type="text" value="capable"><br>
<label>to_be_shown_individually</label> <input id="to_be_shown_individually" type="checkbox" checked=""> <br>
<label>check_for_geometry</label><input id="check_for_geometry" type="checkbox" checked=""><br>
</div>
Adjust your html to include classes or some other identifier, since you cannot have two elements with same ids, things like #topic_level, Probably add a class to help with selection, something like below should help
<div id="point_in_first_quad" class="collapse valueDiv">
<label class="tts-label">tts</label> <input id="tts" class="tts-value" type="text" value="10"><br>...
You added classes to element you want to use in your result.
Adjust the following to make your result object
var finalResult = [];
$('#accordion div').each(function(index, item) {
var $it = $(item);
var ob = {};
ob['name'] = $it.find('.tts-label').text();
ob['tts.value'] = $it.find('.tts-value').val();
ob['ifcheckboxcheck'] = $it.find('[type="checkbox"]').is(":checked");
finalResult.push(ob);
});
Since you have two checkbox field, add a class selector to the one you want to use in result.
Im a bit lost and figured you guys might be able to help.
What I am trying to do:
I have a form where the user will dynamically add fields and then I would like the user to submit that form and display the values on the next page. But the user has to select a dropdown to show the type of data they are submitting inside the text box. For example
--------------------------
- Drop Down -Text Box -
--------------------------
--------------------------
- INT - 123 -
--------------------------
--------------------------
- TEXT - ABC - +
--------------------------
After Form Submit:
INT - 123
TEXT- ABC
Does anyone know how I could do this?
My Code:
<div class="col-md-4">
<div class="values">
<label>Type:</label>
<form method="post" action="values.php">
<div class="form-group multiple-form-group input-group">
<div class="input-group-btn input-group-select">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
<span class="concept">int</span> <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu">
<li>int</li>
<li>text</li>
</ul>
<input type="hidden" class="input-group-select-val" name="contacts['type'][]" value="int">
</div>
<input type="text" name="contacts['value'][]" class="form-control">
<span class="input-group-btn">
<button type="button" class="btn btn-success btn-add">+</button>
</span>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
<script>
(function ($) {
$(function () {
var addFormGroup = function (event) {
event.preventDefault();
var $formGroup = $(this).closest('.form-group');
var $multipleFormGroup = $formGroup.closest('.multiple-form-group');
var $formGroupClone = $formGroup.clone();
$(this)
.toggleClass('btn-success btn-add btn-danger btn-remove')
.html('–');
$formGroupClone.find('input').val('');
$formGroupClone.find('.concept').text('int');
$formGroupClone.find('.input-group-select-val').text('int');
$formGroupClone.insertAfter($formGroup);
var $lastFormGroupLast = $multipleFormGroup.find('.form-group:last');
if ($multipleFormGroup.data('max') <= countFormGroup($multipleFormGroup)) {
$lastFormGroupLast.find('.btn-add').attr('disabled', true);
}
};
var removeFormGroup = function (event) {
event.preventDefault();
var $formGroup = $(this).closest('.form-group');
var $multipleFormGroup = $formGroup.closest('.multiple-form-group');
var $lastFormGroupLast = $multipleFormGroup.find('.form-group:last');
if ($multipleFormGroup.data('max') >= countFormGroup($multipleFormGroup)) {
$lastFormGroupLast.find('.btn-add').attr('disabled', false);
}
$formGroup.remove();
};
var selectFormGroup = function (event) {
event.preventDefault();
var $selectGroup = $(this).closest('.input-group-select');
var param = $(this).attr("href").replace("#","");
var concept = $(this).text();
$selectGroup.find('.concept').text(concept);
$selectGroup.find('.input-group-select-val').val(param);
}
var countFormGroup = function ($form) {
return $form.find('.form-group').length;
};
$(document).on('click', '.btn-add', addFormGroup);
$(document).on('click', '.btn-remove', removeFormGroup);
$(document).on('click', '.dropdown-menu a', selectFormGroup);
});
})(jQuery);
</script>
I'm just a beginner I want to create button for remove clone but I can't.
This is my code but it isn't work. Please help me to know where did I wrong.
PS. Sorry for my poor English
HTML
<div class="docu">
<div class="row">
<div class="col-sm-2"></div>
<div class="col-lg-7" id="Freport" name="Freport">
<div class="input-group">
<div class="input-group-btn">
<select name="tell" id="tell" class="btn btn-default dropdown-toggle">
<option value="0"></option>
<option value="1"></option>
<option value="2"></option>
<option value="3"></option>
</select>
</div><!--End row-->
<input type="text" class="form-control" aria-label="..." placeholder="...">
</div><!-- /btn-group -->
</div><!-- /input-group -->
<div class="col-sm-1">
<button type="submit" id="btnClonereport"><span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span></button>
<button type="submit" id="btnDelreport"><span class="glyphicon glyphicon-minus-sign" aria-hidden="true"></span></button>
</div>
<div id="container4">
</div>
JS This is my script I can clone but I can't remove clone.
<script type="text/javascript">
$(function () {
$("#btnClonereport").bind("click", function () {
var index = $("#container4 select").length + 1;
//Clone the DropDownList
var fre = $("#Freport").clone();
var fre2 = $("#orand").clone();
//Set the ID and Name
fre.attr("id", "Freport_" + index);
fre.attr("name", "Freport_" + index);
fre2.attr("id", "orand_" + index);
fre2.attr("name", "orand_" + index);
//[OPTIONAL] Copy the selected value
var selectedValue = $("#Freports option:selected").val();
fre.find("option[value = '" + selectedValue + "']").attr("selected", "selected");
var selectedValue = $("#orands option:selected").val();
fre2.find("option[value = '" + selectedValue + "']").attr("selected", "selected");
//Append to the DIV.
$("#container4").append(fre2);
$("#container4").append(fre);
$("#container4").append("<br /><br />");
});
$("#btnDelreport").bind("click", function(){
$(this).closest("#container4").remove();
});
});
</script>
So you want to remove all form clones? Try this for your delete button action:
EDIT: If you want to remove the last occurance, that makes things much simpler.
$("#btnDelreport").bind("click", function(){
$('#container4').children('.col-lg-7').last().remove();
});
I have a form, I want to append a entire div every time a button is clicked. The code works but after few seconds the appended div automatically disappears. don't get any errors.
I am using jQuery 2.1.3. Here is my code in JS Fiddle:
https://jsfiddle.net/sathyabaman/jgdLtu4d/
My code:
<form method="POST" id="form_property" enctype="multipart/form-data">
<div class="row">
<div class="span4" id="image">
<h3><strong>4.</strong> <span>Add Images to your Property (Maximum : 6 Images)</span></h3>
<div id="clone_image" class="fileupload fileupload-new ">
<label class="control-label">Image file</label>
<div class="input-append">
<div class="uneditable-input"> <i class="icon-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</div> <span class="btn btn-file">
<span class="fileupload-new">Select file</span>
<span class="fileupload-exists">Change</span>
<input type="file" name="files1" accept="image/*" />
</span>
</div>
</div>
</div>
<!-- /.span4 -->
</div>
<!-- /.row -->
<br/> <a id="another_image" class="btn btn-primary btn-small list-your-property" href="">Add Another Image</a>
<br/>
<br/>
<input type="submit" name="submit" value=" Save images " class="btn btn-primary btn-large" style="float: left; width: 370px; height: 50px; margin-top: 10px">
</form>
jquery
$(document).ready(function(){
var count = 2;
$('#another_image').click (function(){
var clonedEl = $('#clone_image').first().clone()
clonedEl.find(':file').attr('name','files'+count)
if(count < 7){
if(count == 6){ $('#another_image').hide();}
$(clonedEl).appendTo("#image");
count++;
}
});
});
Thank you..
You need to prevent the default action of the anchor click, which is to navigate to the target page.
Since you have specified an empty href it reloads the same page that is why you can see the new element and then it appears to be disappearing.
$(document).ready(function () {
var count = 2;
$('#another_image').click(function (e) {
//e.preventDefault()
var clonedEl = $('#clone_image').first().clone()
clonedEl.find(':file').attr('name', 'files' + count)
if (count < 7) {
if (count == 6) {
$('#another_image').hide();
}
$(clonedEl).appendTo("#image");
count++;
}
});
});
Demo: Fiddle