EDIT: Just so I asks questions better next time. I got a -1 what did I do wrong?
I'm adding quite a lot of html dynamically and want to be able to remove them also one by one.
Below the JQuery. I want to be able to remove the whole $("#row1' + (counter) + '") div including all divs in it by clicking the remove button under it.
Here's a fiddle: http://jsfiddle.net/FullContCoder/Sf9r5/1/
Thanks a lot in advance!
$(document).ready(function() {
var counter = 0;
$(".addButton").click(function() {
var test = $( '<div id="row1' + (counter) + '" class="row"><div class="col-md-2"><p><small>Placement Name:</small></p><input id="inputPlacement' + (counter) + '" type="text" class="form-control input-sm" name="placementName" placeholder="ex: Homepage">' +
'</div><div class="col-md-3"><p><small>URL:</small></p><input id="inputURL" type="url" class="form-control input-sm" name="url" placeholder="ex: http://www.allure.com"></div>' +
'<div class="col-md-2"><div class="row"><div class="col-md-12"><p><small>Select a Date and Time:</small></p></div></div><div class="row"><div class="col-md-12">' +
'<div class="input-append date" id="dp3" data-date="12-02-2012" data-date-format="dd-mm-yyyy"><input class="span2" size="16" type="text" value="12-02-2012" readonly=""><span class="add-on"><i class="icon-calendar"></i>' +
'</span></div></div></div><div class="row"><div class="input-append bootstrap-timepicker"><input id="timepicker1" type="text" class="input-small"><span class="add-on">' +
'<i class="glyphicon glyphicon-time"></i></span></div></div></div><div class="col-md-2"><p><small>Recurring:</small></p><select id="recurring" class="form-control input-sm">' +
'<option name="daily" value="daily">Daily</option><option name="weekly" value="weekly">Weekly</option><option name="month" value="month">Month</option></select></div>' +
'<div class="col-md-2"><p><small>Day of Week:</small></p><div class="row"><div class="col-md-6"><label class="checkbox-inline"><input id="mon" name="test" type="checkbox" value="1"> Mon</label>' +
'</div><div class="col-md-6"><label class="checkbox-inline"><input id="fri" name="test" type="checkbox" value="1"> Fri</label></div></div><div class="row"><div class="col-md-6">' +
'<label class="checkbox-inline"><input id="tue" name="test" type="checkbox" value="1"> Tue</label></div><div class="col-md-6"><label class="checkbox-inline">' +
'<input id="sat" name="test" type="checkbox" value="1"> Sat</label></div></div><div class="row"><div class="col-md-6"><label class="checkbox-inline">' +
'<input id="wen" name="test" type="checkbox" value="1"> Wed</label></div><div class="col-md-6"><label class="checkbox-inline">' +
'<input id="sun" name="test" type="checkbox" value="1"> Sun</label></div></div><div class="row"><div class="col-md-6"><label class="checkbox-inline">' +
'<input id="thu" name="test" type="checkbox" value="1"> Thu</label></div></div></div><div class="col-md-1"><p><small>Remove:</small></p>' +
'<button type="button" class="removeButton btn btn-default btn-sm"><span class="glyphicon glyphicon-minus-sign"></span></button></div></div>' )
$('.removeButton').click(function() {
$("#row1' + (counter) + '").remove();
});
counter++;
$("#row1").after(test);
});
});
You should use event delegation to add events to dynamically created elements. And use .closest() to get the first element that matches the selector. Try this:
$(document).on('click','.removeButton',function() {
$(this).closest("div.row").remove();
});
You need to move your remove button click handler outside of add button click handler.
DEMO
You can try it.
$(document).on('click', '.removeButton', function(){
$('#row1' + counter).remove();
});
1) You need to use event delegation here to bind click event to your button since it has been added dynamically to the DOM.
2) Use .closest() to remove the closest matching ancestor .row and remove redundant counter variable here:
3) You also need to move your click handler of remove button outside of the click handler of the add button.
Final code should look something like this:
$(document).ready(function () {
$(".addButton").click(function () {
var test = .....
$("#row1").after(test);
});
$('.removeButton').click(function () {
$(this).closest(".row").remove();
});
});
Updated Fiddle
Related
I am adding textboxes through jquery and for one text box it is removing perfeclty but when I add two textboxes then it does now remove both.
this is jquery
<script>
$(document).ready(function($){
$('.product-form .add-product').click(function(){
var n = $('.text-product').length + 1;
var product_html = $('<p class="text-product"><label for="product' + n + '">Name <span class="product-number">' + n + '</span></label> <input required type="text" name="productnames[]" value="" id="product' + n + '" /> <label for="productprice' + n + '">Price <span class="product-number">' + n + '</span></label> <input required type="text" name="productprices[]" value="" id="productprice' + n + '" />Remove</p>');
product_html.hide();
$('.product-form p.text-product:last').after(product_html);
product_html.fadeIn('slow');
return false;
});
$('.product-form').on('click', '.remove-category', function(){
$(this).parent().fadeOut("slow", function() {
$(this).remove();
$('.product-number').each(function(index){
$(this).text( index + 1 );
});
});
return false;
});
});
</script>
and this is my html
<div>
<form>
<div class="product-form">
<p class="text-product">
<label for="product1">Name <span class="product-number">1</span></label>
<input required type="text" name="productnames[]" value="" id="product1" />
<label for="product1">Price <span class="product-number">1</span></label>
<input required type="text" name="productprices[]" value="" id="product1" />
<div>
<a class="add-product" href="#">Add More</a>
</div>
</p>
</div>
<div>
<input type="submit" name="submitDetails" value="Finish"/>
</div>
</form>
</div>
If only one textbox for instance productnames is added then it removal function works but when I add botch productnames and productprices textbox removal function does not remove both
Your code should read $('.product-form').on('click', '.remove-product', function() rather than 'click', '.remove-category'. Also, don't place the Add More div element inside the paragraph element. The numbering also breaks a bit, but you can figure that out.
i have a conflict with jquery and can not find a correct solution, every time something breaks, i have a form that i add one input and one select at the time dynamically, by default the html form have on input and one select, and after adding new fields if is required.
The problem is that the fields are added dinamically with jquery and can be removed as well, but if you add a few new fields and remove just the last one the form will not be working anymore, can not be added new fields, but if you remove a field from the middle than it is fine is working.
I need to fix if you remove even the last element to be abble to add again new fields.
Please see the example below.
HTML
<form action="" method="post" enctype="multipart/form-data" class="form-horizontal">
<span class="multiple-field-container-add">
<span class="content-panel-flat-raw-double-sub">
<span class="content-panel-flat-raw-double-sub-raw has-feedback has-feedback-left">
<label>IBAN</label>
<input class="form-control" id="0-iban" name="0-iban" type="text" value="">
</span>
<span class="content-panel-flat-raw-double-sub-raw">
<span class="content-panel-flat-raw-double-sub-raw-double-raw">
<label>Currency</label>
<select class="select select2-hidden-accessible" id="0-currency" name="0-currency" tabindex="-1" aria-hidden="true"><option value="-">Select currency</option><option value="USD">USD</option><option value="EUR">EUR</option></select>
</span>
<span class="content-panel-flat-raw-double-sub-raw-double-raw">
<b><i class="icon-plus2"></i></b> Add new
</span>
</span>
</span>
</span>
</form>
Jquery
var next = 1;
$(".multiple-add-input").click(function(e){
e.preventDefault();
var addto = "#" + next + "-iban";
next = next + 1;
var newIn = '<span class="content-panel-flat-raw-double-sub">'+
'<span class="content-panel-flat-raw-double-sub-raw has-feedback has-feedback-left">'+
'<label>IBAN</label>'+
'<input class="form-control" id="' + (next) + '-iban" name="' + (next) + '-iban" type="text" value="">'+
'<div class="form-control-feedback">'+
'<i class="icon-font-size"></i>'+
'</div>'+
'</span>'+
'<span class="content-panel-flat-raw-double-sub-raw">'+
'<span class="content-panel-flat-raw-double-sub-raw-double-raw">'+
'<label>Currency</label>'+
'<select name="' + (next) + '-currency" id="' + (next) + '-currency" class="select">'+
'<option value="EUR">EUR</option>'+
'<option value="USD">USD</option>'+
'</select>'+
'</span>'+
'<span class="content-panel-flat-raw-double-sub-raw-double-raw">'+
'<div class="btn bg-teal-400 btn-labeled btn-custom-width remove-me" onclick="_multiple_field_remove_('+ (next) +')"><b><i class="icon-cancel-square2"></i></b> Remove</div>'+
'</span>'+
'</span>'+
'</span>';
alert(next);
var newInput = $(newIn);
$(addto).parent().parent().after(newInput);
$('.select').select2();
_multiple_field_remove_ = function(id){
alert(id);
$('#'+ id +'-iban').parents('span.content-panel-flat-raw-double-sub').remove();
};
ionluchian
the reason cause the issue,it's the number next.
when you delete the last element, and you click add button next,
var addto = "#" + next + "-iban";
...
// can't find item 'addto',so it's not work
$(addto).parent().parent().after(newInput);
this code can't find the last items at all.
Please use above instead:
change: $(addto).parent().parent().after(newInput);
to : $('.multiple-field-container-add').append(newInput)
This is not the best looking end result, but its working
$(function(){
addElement();
});
function addElement(){
$(".multiple-add-input").on('click', function(e){
e.preventDefault();
$(this).off('click');
var next = parseInt($('.iban-input').last().attr('id'));
var addto = "#" + next + "-iban";
next++;
var newIn = '<span class="content-panel-flat-raw-double-sub">'+
'<span class="content-panel-flat-raw-double-sub-raw has-feedback has-feedback-left">'+
'<label>IBAN</label>'+
'<input class="form-control iban-input" id="' + (next) + '-iban" name="' + (next) + '-iban" type="text" value="">'+
'<div class="form-control-feedback">'+
'<i class="icon-font-size"></i>'+
'</div>'+
'</span>'+
'<span class="content-panel-flat-raw-double-sub-raw">'+
'<span class="content-panel-flat-raw-double-sub-raw-double-raw">'+
'<label>Currency</label>'+
'<select name="' + (next) + '-currency" id="' + (next) + '-currency" class="select">'+
'<option value="EUR">EUR</option>'+
'<option value="USD">USD</option>'+
'</select>'+
'</span>'+
'<span class="content-panel-flat-raw-double-sub-raw-double-raw">'+
'<div class="btn bg-teal-400 btn-labeled btn-custom-width remove-me" id="remove-'+ (next) +'"><b><i class="icon-cancel-square2"></i></b> Remove</div>'+
'</span>'+
'</span>'+
'</span>';
// Add element
$(addto).parent().parent().after(newIn);
// Bind removing
$('.remove-me')
.off('click')
.on('click', function(){
removeElement($(this).attr('id'));
});
// Bind adding
addElement();
});
}
function removeElement(id){
$('#'+id).parent().parent().parent().remove();
}
.content-panel-flat-raw-double-sub{
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" enctype="multipart/form-data" class="form-horizontal">
<span class="multiple-field-container-add">
<span class="content-panel-flat-raw-double-sub">
<span class="content-panel-flat-raw-double-sub-raw has-feedback has-feedback-left">
<label>IBAN</label>
<input class="form-control iban-input" id="0-iban" name="0-iban" type="text" value="">
</span>
<span class="content-panel-flat-raw-double-sub-raw">
<span class="content-panel-flat-raw-double-sub-raw-double-raw">
<label>Currency</label>
<select class="select select2-hidden-accessible" id="0-currency" name="0-currency" tabindex="-1" aria-hidden="true"><option value="-">Select currency</option><option value="USD">USD</option><option value="EUR">EUR</option></select>
</span>
<span class="content-panel-flat-raw-double-sub-raw-double-raw">
<b><i class="icon-plus2"></i></b> Add new
</span>
</span>
</span>
</span>
</form>
I have the below code in my html page, the issue is with the multiselect checkbox of the div element of id 'alot'
<div id="pagePreferences" class="pageDefault pageAlertsPreferences" data-role="page" data-class="com/xyz/abc/Controller">
<div id="header" data-role="header">
<!-- Loads header here -->
</div>
<div class="contentRegular" data-role="content">
<div data-role="main" class="ui-content" data-theme="c">
<label class="inline">Yes or NO</label>
<select id="togButton" class="slider" name="flip-1" data-role="slider">
<option value="off">Off</option>
<option value="on">On</option>
</select>
<div data-role="fieldcontain" id="alot">
<fieldset data-role="controlgroup">
<div style="font-weight: bold" id="checkBoxes">Business Category:</div>
<input type="checkbox" value="All" class="checkBoxClass" id="ckbCheckAll" />
<label for="ckbCheckAll">All</label>
<input type="checkbox" value="29" class="checkBoxClass" id="29" />
<label for="29">ABC</label>
<input type="checkbox" value="30" class="checkBoxClass" id="30" />
<label for="30">BCD</label>
<input type="checkbox" value="31" class="checkBoxClass" id="31" />
<label for="31">CDE</label>
</fieldset>
</div>
</div>
</div>
<div id="navMenu" data-role="panel" data-animate="false">
<!-- Navigation Menu is loaded here -->
</div>
</div>
First i have hardcoded the values like the lables ( ABC,BCD,CDE). This works fine and i get the output like below.
But when i want to generate the muliselect cheboxes content from the javascript file(com/xyz/abc/Controller),
i am not getting the multiselect checkbox in a proper format
Here is the screen shot
Here is the html :
<div data-role="fieldcontain" id="alot">
</div> -->
Javascript file :
var prefix = '<fieldset data-role="controlgroup">' +
'<div style="font-weight: bold" id="checkBoxes">Business Units:</div>' +
'<input type="checkbox" value="All" class="checkBoxClass" id="ckbCheckAll" />' +
'<label for="ckbCheckAll">All</label>';
var subfix = '</fieldset>';
var html = "";
$('#alot').append(prefix);
for (generate the data from db) {
html = '<input type="checkbox" value="' + unitID + '" class="checkBoxClass" id="' + unitID + '"' + '/>';
html = html + '<label for="' + unitID + '"' + '>' + unitName + '</label>';
$('#alot').append(html);
}
$('#alot').append(subfix);
What might be missing here ? Why the look & feel of the multi select checkboxes is not same when I generate the content dynamically ?
For dynamically added elements, you should enhance them manually using jQM's methods. The simplest way is using .enhanceWithin() called on parent div. This method will create any widget within that div in spite of its' type.
/* create controlgroup and append "All" checkbox to it */
var ctrlgrp = $("<div/>", {
"data-role": "controlgroup",
id: "checkBoxes"
}).append('<input type="checkbox" value="All" class="checkBoxClass" id="ckbCheckAll" /><label for="ckbCheckAll">All</label>');
/* loop through your data array and append checkboxes to ctrlgrp */
for (var i = 0; i <= 5; i++) {
ctrlgrp.append('<input type="checkbox" value="value' + i + '" class="checkBoxClass" id="cb' + i + '"' + '/><label for="cb' + i + '"' + '>Checkbox ' + i + '</label>');
}
/* append all elements to "alot" div and then enhance the elements */
$("#alot")
.append(ctrlgrp)
.enhanceWithin();
/* check/uncheck checkboxes
with change event delegated to it
since it's dynamically added */
$("#alot").on("change", "#ckbCheckAll", function () {
$(this)
.closest(".ui-controlgroup")
.find("[type=checkbox]")
.prop("checked", $(this).prop("checked"))
.checkboxradio("refresh");
});
Demo
I face a little problem in below code.
I write below code. Unable to find out what's wrong in this code :
HTML:
<div class="all">
<div class="info">
<label>Degree <input type="text" class="row[0][degree]"></label>
<label>School <input type="text" class="row[0][school]"></label>
<label>Grade <input type="text" class="row[0][grade]"></label>
</div>
</div>
<button class="add_button" onclick="add_new()">Add Another</button>
JavaScipt:
var counter = 1;
function add_new() {
$('.all').append('
<div class="info">/
<label>Degree <input type="text" class="row[' + counter + '][degree]"></label>/
<label>School <input type="text" class="row[' + counter + '][school]"></label>/
<label>Grade <input type="text" class="row[' + counter + '][grade]"></label>/
</div>'
counter++;
);
}
Your counter variable doesnt have any relevence, since it is declared locally. If you want to increment the counter each time when calling this function, declare it globally. Also there are some syntax errors in the code, Your code should look like
var counter = 0;
function add_new() {
$('.all').append('<div class="info">\
<label>Degree <input type="text" class="row[' + counter + '][degree]"></label>\
<label>School <input type="text" class="row[' + counter + '][school]"></label>\
<label>Grade <input type="text" class="row[' + counter + '][grade]"></label>\
</div>'
);
counter++;
}
Try counter increment after closing the .append() method.
Instead of using onclick,do it like this with clean way:
HTML:
<button class="add_button">Add Another</button>
JQUERY:
$(document).ready(function(){
var counter = 0;
$(".add_button").click(function(){
$('.all').append('
<div class="info">/
<label>Degree <input type="text" class="row['+counter+'][degree]"></label>/
<label>School <input type="text" class="row['+counter+'][school]"></label>/
<label>Grade <input type="text" class="row['+counter+'][grade]"></label>/
</div>'
);
counter++;
});
})
counter has to be global and incremented outside of $.append
var counter = 0;
function add_new(){
$('.all').append('<div class="info"><label>Degree <input type="text" class="row['+counter+'][degree]"></label><label>School <input type="text" class="row['+counter+'][school]"></label><label>Grade <input type="text" class="row['+counter+'][grade]"></label></div>');
counter++;
}
JSFiddle
One way you can append HTML into the DOM without worrying about really long strings is:
$('.all').append(
$('<div class="info"/>').html(
$('<label/>').html( 'Degree ' ).append('<input type="text" class="row[' + counter + '][degree]">')
)
.append(
$('<label/>').html( 'School ' ).append( '<input type="text" class="row[' + counter + '][school]">' )
)
.append(
$('<label/>').html( 'Grade ' ).append( '<input type="text" class="row[' + counter + '][grade]">' )
)
);
It may be a few more lines, but I find it cleaner, easier to read (when your mind is in JS/jQuery mode) and easier to code .... ... as you can see if there's an object it's quite easy to iterate the object and generate the required HTML
Why when I add the same html code with javascript jquery I loose margin ?
Try this jsfiddle and you will understand me.
jQuery
function addphone() {
$( "#phonedetails" ).append( '<div >' +
'<label>phone :</label>' +
'<input type="text" /> ' +
'<input type="button" onclick="addphone()"/>' +
'</div>');
}
HTML
<div id="phonedetails">
<div>
<label>phone :</label>
<input type="text" />
<input type="button" onclick="addphone();"/>
</div>
</div>
It isn't a margin, it is a space (i.e. what you get when you press the space bar) between the label and the input. It is missing in the code generated from JS.
Change:
'<label>phone :</label>' +
To:
'<label>phone :</label> ' +
// ^ space here
You aren't losing margins, you're losing whitespace:
http://jsfiddle.net/3md9S/2/
$( "#phonedetails" ).append( '<div >' +
'<label>phone :</label> ' + // SINGLE SPACE ADDED HERE
'<input type="text" /> ' +
'<input type="button" onclick="addphone()"/>' +
'</div>');
That is just a white space in your html.
Also you don't have to write html again to append , you can clone it -
$( "#phonedetails" ).append($('#phonedetails div').eq(0).clone());
Demo --> http://jsfiddle.net/3md9S/7/