How to delete last object of an input array? - javascript

I created a dynamic form which adds 3 new input fields if the user clicks a button. However, my delete button deletes the first added fields, which I don't want. How can I delete the last added input fields?
Below is my code for adding and deleting the fields.
$(document).ready(function () {
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 0; //initial count
$(add_button).click(function (e) {
e.preventDefault();
x++;
$(wrapper).append('<div id="names">Name: <input type="text" name="names[]"/></div>');
$(wrapper).append('<div id="ages">Age: <input type="text" name="ages[]"/></div>');
$(wrapper).append('<div id="numbers">Number: <input type="text" name="numbers[]"/><br><br></div></div>');
});
$(wrapper).on("click", ".remove_person", function (e) {
e.preventDefault();
if(x > 0) {
$("#names").remove();
$("#ages").remove();
$("#numbers").remove();
x--;
}
})
});
Below is my code for the fields in the HTML.
<b>People:</b><br>
<div class="input_fields_wrap" id="input_fields_wrap">
<button class="add_field_button">ADD</button>
<button id="remove_person" class="remove_person">REMOVE</button>
<br>
</div>

Firstly, You're using duplicate id's. please use class names instead.
use the jquery's last function like below
$(document).ready(function () {
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 0; //initial count
$(add_button).click(function (e) {
e.preventDefault();
x++;
$(wrapper).append('<div class="names">Name: <input type="text" name="names[]"/></div>');
$(wrapper).append('<div class="ages">Age: <input type="text" name="ages[]"/></div>');
$(wrapper).append('<div class="numbers">Number: <input type="text" name="numbers[]"/><br><br></div></div>');
});
$(wrapper).on("click", ".remove_person", function (e) {
e.preventDefault();
if(x > 0) {
$(".names").last().remove();
$(".ages").last().remove();
$(".numbers").last().remove();
x--;
}
})
});

An alternative to using class and .last() is to put the button into the person wrapper
To delete, use closest to remove the wrapper the button is in (so have a wrapper for each person)
$(document).ready(function () {
var x = 0; //initial count
$(".add_field_button").on("click",function (e) {
var $pWrapper = $('<div/>').addClass("person"); //Fields wrapper
e.preventDefault();
x++;
$pWrapper.append('<button type="button" class="remove_person">REMOVE</button>')
.append('<div class="names">Name: <input type="text" name="names[]"/></div>')
.append('<div class="ages">Age: <input type="text" name="ages[]"/></div>')
.append('<div class="numbers">Number: <input type="text" name="numbers[]"/><br><br></div></div>')
.appendTo("#input_fields_wrap");
});
$("#input_fields_wrap").on("click", ".remove_person", function (e) {
e.preventDefault();
$(this).closest(".person").remove();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<b>People:</b><br>
<div class="input_fields_wrap" id="input_fields_wrap">
<button type="button" class="add_field_button">ADD</button>
<br>
</div>

Related

how to get sum of input fields using jquery

this is my script to add input fields dynamically, in this part, the max of fields is 10.
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) {
x++;
var form_colis = '<div><input type="text" placeholder="Poids" name="poids[]"/> <input type="text" placeholder="Longueur" name="longueurs[]"/> <input type="text" placeholder="Largeur" name="largeurs[]"/> <input type="text" placeholder="Hauteur" name="hauteurs[]"/>Delete</div>';
//$(wrapper).append('<div><input type="text" name="mytext[]"/>Delete</div>'); //add input box
$(wrapper).append(form_colis); //add input box
} else {
alert('You Reached the limits')
}
});
$(wrapper).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container1">
<button class="add_form_field">Add New Field
<span style="font-size:16px; font-weight:bold;">+ </span>
</button>
<div>
<input type="text" placeholder="Poids" name="poids[]">
<input type="text" placeholder="Longueur" name="longueurs[]">
<input type="text" placeholder="Largeur" name="largeurs[]">
<input type="text" placeholder="Hauteur" name="hauteurs[]">
</div>
</div>
Now, I want to add fields in function of the sum of previous fields name. eg. for fields name poids[], if the sum is higher than 100, the user can't add fieldset, else, he can.
I hope that you understand what I mean.
thank you in advance
Here is a version that will calculate. I made the code shorter too - please note the CSS changes and the added class to item div
I assume you only want to test that poids > 100 ?
$(function() {
var max_fields = 10;
var $wrapper = $(".container1");
var add_button = $(".add_form_field");
$(add_button).click(function(e) {
e.preventDefault();
const vals = $("> .item input[name^=poids]",$wrapper).map(function() { return +this.value }).get()
const val = vals.length === 0 ? 0 : vals.reduce((a, b) => a + b);
if ($("> .item",$wrapper).length < max_fields && val < 100) {
const $form_colis = $(".item").first().clone();
$form_colis.find("input").val("");
$wrapper.append($form_colis); //add input box
} else {
alert('You Reached the limits')
}
});
$wrapper.on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
})
});
.container1 .item:first-of-type .delete {
display: none;
}
.delete { text-decoration: none; color: red; }
.add_form_field { white-space: nowrap; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="add_form_field">Add New Field ✚</button>
<div class="container1">
<div class="item">
<input type="text" placeholder="Poids" name="poids[]">
<input type="text" placeholder="Longueur" name="longueurs[]">
<input type="text" placeholder="Largeur" name="largeurs[]">
<input type="text" placeholder="Hauteur" name="hauteurs[]">
Delete
</div>
</div>
If I understood your problem correctly, then check this solution, modified by me. If the sum of all fields is exactly less than 100, then new fields are added, otherwise they are not added. Was it necessary?
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 1;
$(add_button).click(function(e) {
e.preventDefault();
$('.inputs:last-of-type').each(function(){
var sum_inputs = 0;
$(this).find('input').each(function(){
sum_inputs += parseInt($(this).val());
});
if (x < max_fields && sum_inputs < '100') {
x++;
var form_colis = '<div class="inputs"><input type="text" placeholder="Poids" name="poids[]"/> <input type="text" placeholder="Longueur" name="longueurs[]"/> <input type="text" placeholder="Largeur" name="largeurs[]"/> <input type="text" placeholder="Hauteur" name="hauteurs[]"/>Delete</div>';
//$(wrapper).append('<div><input type="text" name="mytext[]"/>Delete</div>'); //add input box
$(wrapper).append(form_colis); //add input box
} else {
alert('You Reached the limits')
}
});
});
$(wrapper).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container1">
<button class="add_form_field">Add New Field
<span style="font-size:16px; font-weight:bold;">+ </span>
</button>
<div class="inputs">
<input type="text" placeholder="Poids" name="poids[]">
<input type="text" placeholder="Longueur" name="longueurs[]">
<input type="text" placeholder="Largeur" name="largeurs[]">
<input type="text" placeholder="Hauteur" name="hauteurs[]">
</div>
</div>

Attaching Events To Dynamically Created Elements With Javascript

I add input dynamically and write event for this input. Event work, but all the second inputs are the same s. I want to do event for each other.
JavaScript:
$(document).ready(function() {
var max_fields = 4; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function (e) {
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input id="test" class="test" type="text" name="mytext[]"/>Remove<br><input id="test2" class="test2" type="text" name="mytext2[]"></div></div>'); //add input box
$(".test").on("input", function () {
$(this).closest('div').find('.test2').val($(this).val());
});
}
});
$(wrapper).on("click", ".remove_field", function (e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
});
$(".test").on("input", function () {
$(this).closest('div').find('.test2').val($(this).val());
});
});
HTML:
<div id="input_fields_wrap" class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input id="test" class="test" type="text" name="mytext[]"></div>
<div><input id="test2" class="test2" type="text" name="mytext2[]"></div>
</div>
may you need to see the demo as above...it works as you need..i maked some changes in class or jQuery...
$(document).ready(function() {
var max_fields = 4; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input id="test" class="test dynamic" type="text" name="mytext[]"/>Remove<br><input id="test2" class="test2 dynamic" type="text" name="mytext2[]"></div></div>'); //add input box
$(".test").on("input", function() {
$(this).closest('div').find('.test2').val($(this).val());
});
// Your Event Code Put Here //
// It Find the all input and add event //
}
});
$(wrapper).on("click", ".remove_field", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
});
$(".test").on("input", function() {
$(this).closest('div').find('.test2').val($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="input_fields_wrap" class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div>
<input id="test" class="test" type="text" name="mytext[]"/>
<bR/>
<input id="test2" class="test2" type="text" name="mytext2[]"/>
</div>
</div>
You can add a class to all your dynamically created elements and then attach an event listener to the class before the event is actually created in the following manner:
Assuming the class you'll be giving is dynamic:
$(document).on('event','.dynamic',function(){
console.log($(this));
});
UPDATE:
$(document).on('input','.dynamic',function(){
console.log("Typing in input 1");
});
$(document).on('input','.dynamic2',function(){
console.log("Typing in input 2");
});
$(document).ready(function() {
var max_fields = 4; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input id="test" class="dynamic" type="text" name="mytext[]"/>Remove<div><input id="test2" class="dynamic2" type="text" name="mytext2[]"></div></div>'); //add input box
}
});
$(wrapper).on("click", ".remove_field", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
});
});
And the HTML would be
<div id="input_fields_wrap" class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input id="test" class="dynamic" type="text" name="mytext[]"></div>
<div><input id="test2" class="dynamic" type="text" name="mytext2[]"></div>
</div>
jQuery first find the all tag and add event. so you can need to assign event after add field...
$(document).ready(function() {
var max_fields = 4; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) { //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input id="test" class="test dynamic" type="text" name="mytext[]"/>Remove<div><input id="test2" class="test2 dynamic" type="text" name="mytext2[]"></div></div>'); //add input box
$('.dynamic').on('event',function(){
// Your Code
});
// Your Event Code Put Here //
// It Find the all input and add event //
}
});
$(wrapper).on("click", ".remove_field", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
});
$(".input_fields_wrap").on("input", "input", function() {
$(".input_fields_wrap .test2").val($(".input_fields_wrap .test").val());
});
});

Dynamicall add two form fileds to form

I want add fisrst name and last name fields dynamically to my form. Currenltly I managed to add one field. but how can I add two fields once.
Ex: fname lastname
fname lastname (X remove)
fname lastname (X remove)
(+ add)
my code
html
below is my html code ser
<div class="input_fields_wrap">
<div><input type="text" name="mytext[]"></div>
// I want to add another field with this
</div>
<button class="add_field_button">Add More Fields</button>
js
$(document).ready(function() {
var max_fields = 20; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/>Remove</div>');
}
});
$(wrapper).on("click",".remove_field", function(e){ e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
Well this will work for you:-
$(document).ready(function() {
var max_fields = 20; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var fname_lname = '<div>First Name:- <input type="text" name="fname"/>Last Name:- <input type="text" name="fname"/>Remove</div>'
var x = 1;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++; //text box increment
$(wrapper).append(fname_lname);
}
});
$(wrapper).on("click",".remove_field", function(e){ e.preventDefault(); $(this).parent().remove(); x--;
})
});
checkout the fiddle
https://jsfiddle.net/dhruv1992/em1je2cu/
So first, I removed the hardcoded HTML from your javascript. Then, I moved that to a HIDDEN template element, and just loaded its inner HTML as my template element -- by doing this, I can create as many elements as I might want.
$(document).ready(function() {
var max_fields = 20; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap");
var add_button = $(".add_field_button");
var x = 1;
$(add_button).click(function(e) {
// Here, I load the template's HTML
var myFullTemplate = $(".fields-template").html();
''
e.preventDefault();
if (x < max_fields) {
x++; //text box increment
$(wrapper).append(myFullTemplate);
} else {
$(".add_field_button").hide();
}
});
$(wrapper).on("click", ".remove_field", function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
if ($(".add_field_button").is(":hidden")) {
$(".add_field_button").show();
}
})
});
.fields-template {
display: none;
}
label {
font-weight: bolder;
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input_fields_wrap">
<div>
<input type="text" name="mytext[]">
</div>
// I want to add another field with this
</div>
<button class="add_field_button">Add More Fields</button>
<div class="fields-template">
<div>
<label for="fname">First name:</label>
<input type="text" name="fname[]" />
<label for="lname">Last name:</label>
<input type="text" name="lname[]" />Remove
</div>
</div>
So, to do what you mention in your comment (remove both fields rather than one), simply edit your HTML template to suit your needs. Also, another change: when you hit your max number of items, the add button is hidden (and when you delete one, it shows again).

Obtaining the target ids of dynamic text field

I have a button which adds dynamic columns on clicking that. I tried to get the target id of each column.
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
js
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
alert("target id" + e.target.id); // I get nothing here
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
How to get target ids and also if it has some value I want to print that as well before removing the column for dynamic column added ?
var max_fields = 10,
wrapper = $('.input_fields_wrap'),
add_button = $('.add_field_button'),
x = 1;
$(add_button).click(function(e) {
e.preventDefault();
if (x < max_fields) {
x++;
$(wrapper).append('<div><input id="' + x + '" type="text" name="mytext[]"/>Remove</div>');
}
});
$(wrapper).on('click', '.remove_field', function(e) {
var div = $(this).parent('div'),
input = div.find('input');
e.preventDefault();
console.log('target id:', input.attr('id'));
console.log('target value:', input.val());
div.remove();
x--;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
You aren't giving IDs to the columns !
<div>
<input type="text" name="mytext[]"/>
Remove
</div>
I used the x of your code, var x = 1; //initlal text box count
$(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field" id='+x+'>Remove</a></div>');
https://jsfiddle.net/7yn7apte/4/

Adding removing input fields using jQuery

I am adding input field on clicking the button and at the same time giving remove button to remove the input field.However my remove button is not removing the input field instead it takes me to top of page...
<div class="input_fields_wrap">
<div class="form-group">
<label class="col-md-3 control-label" for="example-text-input">Preferred Work Location</label>
<div class="col-md-3">
<input type="text" id="loc" name="Work_Location[]" class="form-control" >
</div>
<button class="add_field_button">Add More Locations</button>
</div>
</div>
and below is the jQuery to add more textbox when I click the button
<script>
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="form-group"><label class="col-md-3 control-label" for="example-text-input">Preferred Work Location</label><div class="col-md-3"> <input type="text" id="loc" name="Work_Location[]" class="form-control" ></div>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
I have an example for you, you can do it easier
function closeMe(element) {
$(element).parent().remove();
}
function addMore() {
var container = $('#list');
var item = container.find('.default').clone();
item.removeClass('default');
//add anything you like to item, ex: item.addClass('abc')....
item.appendTo(container).show();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul id="list">
<li class="default" style="display: none;">
<input type="text" /><span style="cursor: pointer;" onclick="closeMe(this);">close</span>
</li>
</ul>
<button onclick="addMore();">Add</button>
Also you can use this:
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
Hope this is helpful for you
Thanks
$(document).ready(function() {
var max = 10;
var wrp= $(".input_fields_wrap");
var addBtn = $(".add_field_button");
var x = 1;
$(addBtn ).click(function(e){
e.preventDefault();
if(x < max){
x++;
$(wrp).append('<div class="form-group">
<label class="col-md-3 control-label" for="example-text-input">Preferred Work Location</label>
<div class="col-md-3">
<input type="text" id="loc" name="Work_Location[]" class="form-control" >
</div>
Remove</div>');
}
});
$(wrp).on("click",".remove_field", function(e){ /
e.preventDefault();
$(this).parent('div').remove(); x--;
})
});

Categories