Let's say I have div like this on my page:
<div style="padding-top:10px;" id="message2">
<p>More Links: <span class="fa fa-plus add"></span></p>
<div class="appending_div">
<div class="blog_links">
<p class="blog_linku_1">
Link URL 1: <input type="text" name="blog_linku_1[]"> Link Name 1: <input type="text" name="blog_linkn_1[]">
</p>
</div>
</div>
</div>
So simply if user click on + sign, it will add another input field just like this one with this script:
$(document).ready(function() {
var i = 2;
$('.add').on('click', function() {
var field = '<p class="link'+i+'">Link URL '+i+': <input type="text" name="blog_linku_'+i+'[]"> Link Name '+i+': <input type="text" name="blog_linkn_'+i+'[]"> <span class="glyphicon glyphicon-minus minus" id="minus'+i+'"></span></p>';
$('.appending_div').append(field);
i = i+1;
})
$('#minus'+i+'').click(function(){
$(".link"+i+"").remove();
});
})
And if you mention out, the extra links contains a remove symbol which is a - sign, and by clicking this sign, the paragraph which has the class link"+i+" should be removed.
And now the problem is that the remove icon does not work when you click on it. And the Console bar does not show any error message.
So what is your idea about this, how can I solve this problem?
First, it will be better to attach the event to a common class instead of using incremented values
Example :
var i = 2;
$('.add').on('click', function() {
var field = '<p class="link">Link URL ' + i + ': <input type="text" name="blog_linku[]"> Link Name ' + i + ': <input type="text" name="blog_linkn[]"> <span class="glyphicon glyphicon-minus minus">----</span></p>';
$('.appending_div').append(field);
i++;
});
NOTE: Since you're using input names as array [] you don't have to generate them with indexes.
You need to use the event delegation .on() when you attach the click event to .minus since the elements are generated dynamically :
$('body').on('click','.minus', function() {
$(this).closest('p').remove();
});
$(document).ready(function() {
var i = 2;
$('.add').on('click', function() {
var field = '<p class="link">Link URL ' + i + ': <input type="text" name="blog_linku[]"> Link Name ' + i + ': <input type="text" name="blog_linkn[]"> <span class="glyphicon glyphicon-minus minus">DELETE</span></p>';
$('.appending_div').append(field);
i++;
});
$('body').on('click', '.minus', function() {
$(this).closest('p').remove();
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="padding-top:10px;" id="message2">
<p>More Links: <span class="fa fa-plus add"></span></p>
<div class="appending_div">
<div class="blog_links">
<p class="blog_linku_1">
Link URL 1: <input type="text" name="blog_linku_1[]"> Link Name 1: <input type="text" name="blog_linkn_1[]">
</p>
</div>
</div>
</div>
<br>
<button class="add" type="button">Add</button>
I've restructured your code a bit. See below:
$(document).ready(function() {
var i = 2;
$('.add').on('click', function() {
$('<p class="link' + i + '">Link URL ' + i + ': <input type="text" name="blog_linku_[]" /> Link Name' + i + ': <input type="text" name="blog_linkn_[]"> <span class="fa fa-minus minus"></span></p>')
.appendTo('.appending_div');
i = i + 1;
});
$('.appending_div').on('click.remove', '.minus', function () {
$(this).parent()
.remove();
});
})
<link href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="padding-top:10px;" id="message2">
<p>More Links: <span class="fa fa-plus add"></span></p>
<div class="appending_div">
<div class="blog_links">
<p class="blog_linku_1">
Link URL 1: <input type="text" name="blog_linku_1[]"> Link Name 1: <input type="text" name="blog_linkn_1[]">
</p>
</div>
</div>
</div>
I've simplified the top portion of your code that adds the element to the screen. Since you are using jQuery you can combine a few of these steps with the chaining of their library functions.
For the event handling, because the elements are added dynamically, you need to delegate the events to the new elements. Recall that elements must be present on the page for the event to be bound. Otherwise, the events must be delegated to an existing element. jQuery will handle the abstractions and the "bubbling" of the events to the parent element.
You are adding the #minus element on $(".add") click, so when the DOM loads it cannot find the $("#minus"). You have to add the $("#minus") click function inside the $(".add") click.
Try the below code
$(document).ready(function() {
var i = 2;
$('.add').on('click', function() {
var field = '<p class="link'+i+'">Link URL '+i+': <input type="text" name="blog_linku_'+i+'[]"> Link Name '+i+': <input type="text" name="blog_linkn_'+i+'[]"> <span class="glyphicon glyphicon-minus minus" id="minus'+i+'"></span></p>';
$('.appending_div').append(field);
i = i+1;
$('#minus'+i+'').click(function(){
$(".link"+i+"").remove();
});
});
});
Related
What I want is, I want to generate a new input type = text whenever a plus icon is getting clicked. SO I have written below code for the same.
$('#dvDVRdata1 .add').on('click', function() {
addDynamicTextbox();
});
function addDynamicTextbox() {
//alert('icon clicked');
var numItems = $('#dvDVRdata1').length;
alert(numItems);
if (numItems != 5) {
var lastfieldsid = $('#dvDVRdata1 input').last().attr('id');
if ($('#' + lastfieldsid).val() != "") {
var id = parseInt(lastfieldsid.substr(13, lastfieldsid.length));
var tr2 = $("#dvDVRdata1" + id + "");
var tr = "<tr id='dvDVRdata1" + (id + 1) + "'><td><div class=''><div class=''><div class='' id='dvDVRdata1" + (id + 1) + "'><label>DVR Address</label><span><input type='text' value='' name='nmDVRAddress" + "' id='txtDVRAddress" + (id + 1) + "'/></span></div></span></div></span></div></div><div class='minus'><i class='fa fa-times' aria-hidden='true'></i></div></td></tr>"
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-6" id="dvDVRdata1">
<div class="form-group">
<label for="">DVR Address </label>
<input type="text" class="form-control" id="txtDVRAddress1" runat="server" />
</div>
<div class="add">
<i class="fa fa-plus" aria-hidden="true"></i>
</div>
</div>
Couple of problem in your code.
Use slice(-1) to get last character of id. It's remove your dependency using hardcode substr(13,... and you can use that value to increase new generated id by +1 .
Check length for input using $('.form-group').find('input').length < 5 which check the length of input inside form-group class and user only able to add 5 inputs.
Finally don't forgot to append your generated element on form-group class using $('.form-group').append(tr); .
I also add example to delete added tr using minus class.
Example:
$('#dvDVRdata1 .add').on('click', function() {
addDynamicTextbox();
});
function addDynamicTextbox() {
//alert('icon clicked');
var numItems = $('#dvDVRdata1').length;
if ($('.form-group').find('input').length < 5) {
var lastfieldsid = $('#dvDVRdata1 input').last().attr('id');
if ($('#' + lastfieldsid).val() != "") {
var id = parseInt(lastfieldsid.slice(-1));
var tr2 = $("#dvDVRdata1" + id + "");
var tr = "<tr id='dvDVRdata" + (id + 1) + "'><td><div class=''><div class=''><div class='' id='dvDVRdata" + (id + 1) + "'><label>DVR Address</label><span><input type='text' value='' name='nmDVRAddress" + "' id='txtDVRAddress" + (id + 1) + "'/></span></div></span></div></span></div></div><div class='minus'><i class='fa fa-times' aria-hidden='true'>Remove</i></div></td></tr>";
}
$('#yourid').append(tr);
} else {
alert("warning........")
}
}
$(document).on('click', 'div.minus', function() {
$(this).closest('tr').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-sm-6" id="dvDVRdata1">
<div class="form-group" id="yourid">
<label for="">DVR Address </label>
<input type="text" class="form-control" id="txtDVRAddress1" runat="server" />
</div>
<div class="add">
<i class="fa fa-plus" aria-hidden="true">icon</i>
</div>
</div>
Assuming that you are going to add new input field in div#dvDVRdata1. You need to append the HTMLcontent to that div as following:
$('#dvDVRdata1').append(tr);
The thing is you need to append the element, which you did not do in the code in your question.
As for remove, you also have not done it in your question yet. Here's the example of add and remove.
$(document).ready(function(){
$('.add').on('click', function () {
addDynamicTextbox();
});
$('.del').click(function (e) {
deleteDynamicTextbox(e);
});
});
function addDynamicTextbox() {
//alert('icon clicked');
var numItems = $('.form-group .dvDVRdata').length;
alert(numItems);
if (numItems != 5) {
var formGroup = $('.form-group');
var elem = `<div class="dvDVRdata" id="dvDVRdata${numItems+1}">
<label for="txtDVRAddress${numItems+1}">DVR Address </label>
<input type="text" class="form-control" id="txtDVRAddress${numItems+1}" runat="server" />
</div>`;
formGroup.append(elem);
}
}
function deleteDynamicTextbox() {
//alert('icon clicked');
var numItems = $('.form-group .dvDVRdata').length;
alert(numItems);
if (numItems > 1) {
$(`#dvDVRdata${numItems}`).remove();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/js/all.min.js" integrity="sha512-rpLlll167T5LJHwp0waJCh3ZRf7pO6IT1+LZOhAyP6phAirwchClbTZV3iqL3BMrVxIYRbzGTpli4rfxsCK6Vw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div class="col-sm-6" id="dvDVRdata1">
<div class="form-group">
<div class="dvDVRdata" id="dvDVRdata1">
<label for="">DVR Address </label>
<input type="text" class="form-control" id="txtDVRAddress1" />
</div>
</div>
</div>
<div class="add">
<i class="fa fa-plus" aria-hidden="true"></i>
</div>
<div class="del">
<i class="fa fa-minus" aria-hidden="true"></i>
</div>
I have an issue in showing filenanme to its corresponding field.
Now,
When i browse a file in the appended div,then it's file name is shown in the parent div instead of dynamically appended div.
Form
<!-- start other_docx -->
<div class="img_field">
<div class="j-row ">
<label class="j-label">Other Documents</label>
<div class="j-span9 j-unit">
<label class="j-input j-append-small-btn">
<label class="j-icon-left" for="files[]">
<i class="fa fa-download"></i>
</label>
<div class="j-file-button">
Browse
<!-- <input type="file" name="files[]" onchange="document.getElementById('files[]').value=this.value;"> -->
<input type="file" name="files[]" onchange="setfilename(this.value);">
</div>
<input type="text" id="files[]" readonly="" placeholder="No file selected">
<span class="j-hint">Only: jpg / png / Pdf</span>
</label>
</div>
<div class="j-span3 j-unit">
<div class="" style="margin-top:5px">
<button style="" class="btn btn-sm btn-primary add_more_button">Add more</button>
</div>
</div>
</div>
</div>
<!-- end other_docx -->
setfilename()
<script>
function setfilename(val)
{
var fileName = val.substr(val.lastIndexOf("\\")+1, val.length);
document.getElementById("files[]").value = fileName;
}
</script>
js
$(document).ready(function() {
var max_fields_limit = 10; //set limit for maximum input fields
var x = 1; //initialize counter for text box
$('.add_more_button').click(function(e){ //click event on add more fields button having class add_more_button
e.preventDefault();
if(x < max_fields_limit){ //check conditions
x++; //counter increment
// $('.img_field').append('<div><input type="file" name="files[]" class="form-control"/>Remove</div>'); //add input field
// var name="document.getElementById('files[]').value=this.value;";
$('.img_field').append('<div class="j-row">' +
'<div class="j-span9 j-unit">' +
'<label class="j-input j-append-small-btn">' +
'<label class="j-icon-left" for="files[]">' +
'<i class="fa fa-download"></i>' +
'</label>' +
'<div class="j-file-button"> Browse' +
'<input type="file" name="files[]" onchange="setfilename(this.value);">' +
// '<input type="file" name="files[]" onchange="'+name+'">' +
'</div>' +
'<input type="text" id="files[]" readonly="" placeholder="No file selected">' +
'<span class="j-hint">Only: jpg / png</span>' +
'</label>' +
'</div>' +
'<div class="j-span3 j-unit">' +
'<div class="" style="margin-top:5px">' +
'<button style="" class="btn btn-sm btn-danger remove_field">Remove</button>' +
'</div>' +
'</div>' +
'</div>');
}
});
$('.img_field').on("click",".remove_field", function(e){ //user click on remove text links
e.preventDefault();
// $(this).parent('div').remove();
$(this).closest("div.j-row").remove();
x--;
})
});
and this is what my form looks like..
enter image description here
I'm kinda new to jquery.. any help will be greatly appreciated.
Thank you in advance.!
//Edit
working fine now.I just replaced the id 'files[]' with a unique id for each dynamically created element.
Thanks to Ouroborus for mentioning the mistake.
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 am trying to implement a functionality that user can add and remove two text fields (ie heading, and description) using jquery, add more functionality is works fine but the removing order is not correct.
Hers is the fiddle that shows the problem
Jquery
var append = '<div><div class="form-group"> <label>Day 1</label><input type="text" value="" name="subHeading" class="form-control"></div>';
append += '<div class="form-group"> <label>Description</label> <textarea class="form-control" name="description"></textarea>';
append += '</div><button type="button" class="btn btn-danger remove" id="btnAddMore">Remove</button></div>';
$('#btnAddMore').click(function() {
$('#appendContent:last').before(append);
});
$('body').on('click', '.remove', function() {
//alert('ok');
$(this).parent().remove();
});
Also i need one more thing when a user is click add more button I am showing a label thay shows day 1 if adding another item the it will show day 2 and so on.
Update text of the label after append/remove
Give some class to identify parent element of container.
$('.days').text(function(index) {
return 'Day ' + (index + 1)
});
Updated Fiddle
give class to main div
var append='<div class="minus"><div class="form-group">
in jquery
$(this).closest('.minus').remove();
You can do,
$('#btnAddMore').click(function() {
var clone = $(append).clone()
$('#appendContent').append(clone);
clone.find(".form-group > label").text("Day " + $("#appendContent").children().length);
});
$('body').on('click', '.remove', function() {
//alert('ok');
$(this).parent().remove();
});
Fiddle
Make a copy of the newly created div using clone().
Then change the label inside the clone() using .find(".form-group > label").text()
Get the number of the current div by counting the children of "appendContentDiv"
var appendContentSize = $('#appendContent .appended-element').size();
$('#btnAddMore').click(function(){
var append='<div class="appended-element"><div class="form-group"> <label>Day '+appendContentSize+'</label><input type="text" value="" name="subHeading" class="form-control"></div>';
append+='<div class="form-group"> <label>Description</label> <textarea class="form-control" name="description"></textarea>';
append+='</div><button type="button" class="btn btn-danger remove" id="btnAddMore">Remove</button></div>';
$('#appendContent').append(append);
appendContentSize++
});
$('body').on('click','.remove',function(){
//alert('ok');
if(appendContentSize > 0){
$(this).parent().remove();
appendContentSize--
}
});
https://jsfiddle.net/giantomakin/wsm755vv/8/
Have a look attached snippet :
/* Latest compiled and minified JavaScript included as External Resource */
var append='<div><div class="form-group"> <label></label><input type="text" value="" name="subHeading" class="form-control"></div>';
append+='<div class="form-group"> <label>Description</label> <textarea class="form-control" name="description"></textarea>';
append+='</div><button type="button" class="btn btn-danger remove" id="btnAddMore">Remove</button></div>';
$('#btnAddMore').click(function(){
$('#appendContent:last').before(append);
var i=1;
$('input[type="text"]').each(function(){
$(this).prev().html('Day '+i);
$(this).attr('name', 'subHeading' + i);
$(this).attr('id', 'subHeading' + i);
i++;
});
});
$('body').on('click','.remove',function(){
//alert('ok');
$(this).parent().remove();
var i=1;
$('input[type="text"]').each(function(){
$(this).prev().html('Day '+i);
$(this).attr('name', 'subHeading' + i);
$(this).attr('id', 'subHeading' + i);
i++;
});
});
/* Latest compiled and minified CSS included as External Resource*/
/* Optional theme */
#import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');
body {
margin: 10px;
}
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button type="button" class="btn btn-primary"id="btnAddMore">Addmore</button>
<!--for append -->
<div id="appendContent">
</div>
<!--end append-->
</div>
As well as please have a look attached fiddle.
Demo fiddle
Auto scroll to the focused input field form division.
I'm cloning the form to add more users to add at once.
So it must scroll down to the input field when I click the add buttion
HTML:
$(document).ready(function() {
$('#id_i_fa_add').click(function duplicate() {
$('#id_i_fa_add').off('click');
$('.fa.fa-trash').off('click');
var original = document.getElementById('id_div_add' + i);
var clone = original.cloneNode(true);
$('#' + clone.id + " a i").attr('class', 'fa fa-trash');
$('#' + clone.id + " a i").attr('id', 'id_i_fa_del' + i);
clone.id = "id_div_add" + ++i;
clone.querySelectorAll("[id = 'id_span_error_email" + (i - 1) + "']")[0].id = 'id_span_error_email' + i;
$(clone).find('input').val("");
$(clone).find('span').text("");
document.getElementById('id_form_append').appendChild(clone);
$('#id_form_append input').focus();
$('#id_i_fa_add').on('click', duplicate);
$('.fa.fa-trash').on('click', duplicate_trash);
});
});
function duplicate_trash() {
var trash_id = this.id;
var parent_trash_id = $('#' + trash_id).parents().eq(1).attr('id');
$('#' + parent_trash_id).remove()
}
<form id='id_form_append' action="#">
<div id='id_div_append'>
<div id='id_div_add0' class="panel_box">
<div class="form_group">
<label>Email Address</label>
<div class="form-group form-inline">
<div class="input-group" style="width: 100%;">
<input name="email" type="text" class="form-control" placeholder="e-mail" autofocus>
<div class="input-group-addon">domains</div>
</div>
</div>
<span id='id_span_error_email0' class='class_span0'></span>
</div>
<a class="action" href="#">
<i id='id_i_fa_add' class="fa fa-plus"></i>
</a>
</div>
</div>
</form>
you can scroll to a position using:
$(window).scrollTop(/* pixel count */)
to retrieve the position of any element, use:
$(/* selector */).position()
you then have a simple object containing the position of the selected element. To retrieve the pixel to the top, use:
$(/* selector */).position().top
Note: This will only work correctly if your selector selects exactly one element.