On Click add HTML Elements - javascript

I am stuck with jquery wherein I am trying to add dynamic html elements (on click of +) which should also get removed on clicking on (-).
Each element should have unique name and id say "name_1","name_2"...
But it doesn't seem to going my way.
Here is my code:
$(document).ready(function() {
var maxField = 10;
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var fieldHTML = $('.field_wrapper1').html();
var x = 1;
$('.add_button').click(function() {
if (x < maxField) {
x++;
$('.field_wrapper').append('<div class="field_wrapper1" style = "display:none;margin:20px;"><div><strong>*Upload New Contract Copy :</strong><input type="text" name="text_1" id = "text_1" value="" maxlength="50"/><strong><font color="#ff0000">* </font>Upload New Contract Copy :</strong><input type="file" name="pdf_1" id="pdf_1" accept="application/pdf" /><img src="http://www.allintravellocal.com/images/minus_img.jpg"/><label for="contract_copy_pdf" class="err" id="err_lbl_contract_copy_pdf"></label></div></div>');
}
});
$(wrapper).delegate('.remove_button', 'click', function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
});
});
<div class="field_wrapper">
<div>
<strong><font color='#ff0000'>* </font>Upload New Contract Copy :</strong>
<input type="text" name="contract_copy_text_1" id="contract_copy_text_1" value="" maxlength="50" />
<strong><font color='#ff0000'>* </font>Upload New Contract Copy :</strong>
<input type="file" name="contract_copy_pdf_1" id="contract_copy_pdf_1" accept="application/pdf" /> (*.pdf)
<a href="javascript:void(0);" class="add_button" title="Add field">
<img src="http://www.allintravellocal.com/images/plus_img.jpg" />
</a>
<label for="contract_copy_pdf" class="err" id="err_lbl_contract_copy_pdf"></label>
</div>
</div>
Here is my fiddle :
Demo

Its working as expected but with few things to modify:
DEMO
You have set display:none to your added element and even though its
getting appended its not getting shown in the UI. So just remove
that property as below:
$('.field_wrapper').append('<div class="field_wrapper1" style = "margin:20px;">... }
Use .on instead of .delegate if you are using jquery.js > 1.7 because As of jQuery 1.7, .delegate() has been superseded by
the .on() method according to this
and so the below code changes
Changes
$(wrapper).on('click','.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove();
x--;
});

Why you have this display:none inside field_wrapper1:
<div class="field_wrapper1" style = "display:none;margin:20px;">
You will never see the newly created element unless change to display:block.
And for the increment unique name and id:
Place x++; after appended function like so:
$('.field_wrapper').append('<div class="field_wrapper1" style = "display:block;margin:20px;"><div><strong>*Upload New Contract Copy :</strong><input type="text" name="text_'+x+'" id = "text_'+x+'" value="" maxlength="50"/><strong><font color="#ff0000">* </font>Upload New Contract Copy :</strong><input type="file" name="pdf_1" id="pdf_1" accept="application/pdf" />-<label for="contract_copy_pdf" class="err" id="err_lbl_contract_copy_pdf"></label></div></div>');
x++;

Check this Js Fiddle link, and each elements have unique id and name as you need.
$(document).ready(function(){
var maxField = 10;
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var fieldHTML = $('.field_wrapper1').html();
var x = 1;
$('.add_button').click(function(){
if(x < maxField){
x++;
id='text_'+x;
name="name_"+x;
$('.field_wrapper').append('<div class="field_wrapper1" style = "display:block;margin:20px;"><div><strong>*Upload New Contract Copy :</strong><input type="text" name='+name+' id ='+ id+' value="" maxlength="50"/><strong><font color="#ff0000">* </font>Upload New Contract Copy :</strong><input type="file" name="pdf_1" id="pdf_1" accept="application/pdf" /><img src="http://www.allintravellocal.com/images/minus_img.jpg"/><label for="contract_copy_pdf" class="err" id="err_lbl_contract_copy_pdf"></label></div></div>');
}
});
$(wrapper).delegate('.remove_button','click', function(e){
e.preventDefault();
$(this).parent('div').remove();
x--;
});
});

Related

Dynamically Carry Values from inputs to Dynamically added new inputs

Currently it only adds the value once. I have a list of dropdowns(per this example its just input values that u can manually change) that I change from time to time. When clicking 'add' button, it should carry those values over to the field_wrapper, while dynamically adding new input fields to carry each value.
Meaning, I want it to add each new value selected from "text" and append to each new input text field!
I set the global variables above the function. But not sure why the value only shows up one time, and doesn't add new values each time I click 'add'
I hope this makes sense!
Javascript
// Dynamically Add More Input Fields after Add Button //Add to cart
var maxNum= 20;
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var fieldHTML = '<div><input type="text" id="test" value=""/><img src="remove-icon.png"/></div>'; //New input field html
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxNum){
x++;
var cartID = $('#cID').val(),
cartd = $('#dID').val(),
cartP = $('#price').val()
text=cartID + cartD+ cartP;
$(wrapper).append(field)
$('#test').val(text)
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove();
});
HTML
<input name="cID" class="form-control" type="text" id="cID" value="">
<input name="dID" class="form-control" type="text" id="dID" value="">
<input name="price" class="form-control" type="text" id="price" value="">
<div class="field_wrapper">
</div>
Nothing to do more simply interpolate the html and add text variable as value of id="test" but it is better to use class instead of id.
// Dynamically Add More Input Fields after Add Button //Add to cart
var maxNum= 20;
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var x = 1; //Initial field counter is 1
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxNum){
x++;
var cartID = $('#cID').val(),
cartd = $('#dID').val(),
cartP = $('#price').val()
text=cartID + cartd + cartP;
$(wrapper).append(`<div><input type="text" id="test" value="${text}"/><img src="remove-icon.png"/></div>`)
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="cID" class="form-control" type="text" id="cID" value="">
<input name="dID" class="form-control" type="text" id="dID" value="">
<input name="price" class="form-control" type="text" id="price" value="">
<div class="field_wrapper">
<button class="add_button">Add</button>
</div>

Why won't the newly created input tags stay on page?

Im trying to create new input tags based on the number the user enters. My code will create the correct amount of tags, but they get removed almost immediately. Why?
<form>
<input type='text' id='input' />
<button>Submit</button>
</form>
<div id="box">
</div>
<script>
$(document).ready(function() {
$('button').click(function() {
var x = $('#input').val();
for(var i=0 ; i < x; i++) {
$('<input type="text" /><br>').prependTo('#box');
};
});
});
</script>
call preventDefault on the event to stop the button action from firing
$('button').click(function(e) {
e.preventDefault();
var x = $('#input').val();
for(var i=0 ; i < x; i++) {
$('<input type="text" /><br>').prependTo('#box');
};
});
FIDDLE
Change your existing button to an input with an id and use the id in the JS. Your problem is the form is being submitted when you click button.
http://jsfiddle.net/Delorian/65gLvfdx/
<input type="button" id="update" value="Submit" />

jquery javascript add/remove button

I have a form, where I dynamically want to add additional inputfields. So when I click the "Add"-button, there should appear a new inputfield but now with both an add and remove button. When I now click the "Add" button next to the new inputfield, there shoud appear another new inputfield et. etc. The same goes fro the remove button. So far, so good... my issue is though, that I cant create a new inputfield after clicking "Add"...
So, my code looks like this:
<div id="fields">
<button class="add">Add</button>
<div class="newField">
<div class="check">
<input type="radio" id="field_1" name="correct" required></input>
</div>
<input type="text" id="input_1" required></input>
</div>
</div>
the CSS:
#fields {
width:350px
}
.check{
float:left
}
.add, .remove {
float:right
}
and most important, the javascript:
var InputsWrapper = $("#fields");
var x = InputsWrapper.length;
var FieldCount=1;
$('.add').click(function(e){
FieldCount++;
$(InputsWrapper).append('<div class="newField"><button class="remove">Remove</button><button class="add">Add</button><div class="check"><input type="radio" id="field_'+ FieldCount +'" name="correct"></div><input type="text" id="input_'+ FieldCount +'" /></div></div>');
x++;
return false;
});
$(document).on("click",".remove", function(e){
if( x > 1 ) {
$(this).parent('div').remove();
x--;
}
return false;
});
Here is a DEMO fiddle: http://jsfiddle.net/cwprf03o/
Can someone help me out?
Replace line
$('.add').click(function(e){
with
$(document).on("click", ".add", function(e){
The reason for this is that the click() function binds your function(e){} to .add elements that exist at the time the click() function is called.
The on() method works differently. On the click event it will also search for any .add items that exist at the time the click event is raised.
http://jsfiddle.net/1qq40qex/

Issue with creating clones of HTML div using JQuery

I am trying to create clones of a HTML div. The div has a label and two text boxes inside it. I need to change the label value of the newly created div. Here is my code.
<body>
<div id="PayDiv2">
<label id="PayLbl2">Payment No 2: </label>
<input type="text" />
<input type="text" />
</div>
<div id ="totPayForm" >
<label id="totPayLbl">Total Payment: </label>
<input type="text" />
<input type="text" />
<input type="submit" value="Add new one" onclick="addNewField();
return false;">
</div>
<input type="button" value="Clone box" id="btn" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
var i=3;
//When DOM loaded we attach click event to button
$(document).ready(function() {
$('#btn').click(function() {
var cloned = $('#PayDiv2').clone();
cloned.insertBefore("#totPayForm");
$('#PayLbl2').html("Payment No "+ i++ + ':');
});
});
</script>
</body>
The problem is the place the newly created clones placed. First clone get placed before everything(even though I need to place it after the original div which I used to create divs. )
divs generated after that also get placed at first and, early divs goes down. It is hard to describe here. If you can be kind enough to run my code you will see what the issue is.
I have an another requirement to generate unique ids to cloned divs. Since I am new in JQuery, I found it difficult to generate id's.
I am pleased if you can help me in this case. Thank you all.
The problem is $('#PayLbl2').html("Payment No "+ i++ + ':'); it always changes the first element's label instead of the clone(because of the duplicated ids)...
so use class instead of id
<div class="PayDiv2">
<label class="PayLbl2">Payment No 2:</label>
<input type="text" />
<input type="text" />
</div>
then
var i = 3;
//When DOM loaded we attach click event to button
$(document).ready(function () {
$('#btn').click(function () {
var cloned = $('.PayDiv2').first().clone();
cloned.insertBefore("#totPayForm");
cloned.find('.PayLbl2').html("Payment No " + i+++':');
});
});
Demo: Fiddle
Here it is.
Demo
Make your HTML like below
<div id="PayDiv0" class="PayDiv0">
<label id="PayLbl0" class="PayLbl2">Payment No 2:</label>
<input type="text" />
<input type="text" />
</div>
<div id="totPayForm">
<label id="totPayLbl">Total Payment:</label>
<input type="text" />
<input type="text" />
<input type="submit" value="Add new one" onclick="addNewField();
return false;">
</div>
<input type="button" value="Clone box" id="btn" />
And JS should be like this
var i = 3;
$(document).ready(function () {
$('#btn').click(function () {
var cloned = $('.PayDiv0').first().clone();
var noOfDivs = $('.PayDiv0').length;
cloned.insertBefore("#totPayForm");
cloned.attr('id', 'PayDiv' + noOfDivs);
cloned.find('label').attr('id', 'PayLbl' + noOfDivs);
cloned.find('.PayLbl2').html("Payment No " + i+++':');
});
});
As mentioned in the answer by #Arun P Johny, set the div id PayDiv0
$('#btn').click(function () {
var cloned = $('.PayDiv2').first().clone();
// find total divs with class PayDiv2
var noOfDivs = $('.PayDiv2').length;
cloned.insertBefore("#totPayForm");
// add new id to the cloned div
cloned.attr('id', 'PayDiv' + noOfDivs);
// find the label element inside new div and add the new id to it
cloned.find('label').attr('id', 'PayLbl' + noOfDivs);
cloned.find('.PayLbl2').html("Payment No " + i+++':');
});
this way you can add the dynamic ids to your elements.

Remove element from outside its container

I am trying to create an election simulator. I have a form field and a link to add more fields. Whatever I write in the fields shows up below the fields. When I click on "Remove" it removes the form field but not it's corresponding text below. This is what I want to fix.
html
<h2>Add new party</h2>
<div id="partiesDiv">
<p>
<label for="parties"><input type="text" id="party" size="20" name="party" value="" placeholder="Party name" onkeyup="updateTxt('party','txt');"></label>
</p>
</div>
<div id="text">
<p>
<span id="txt"></span>
</p>
</div>
javascript
$(function() {
var partyDiv = $('#partiesDiv');
var textDiv = $('#text');
var i = $('#partiesDiv p').size() + 1;
$('#addParty').live('click', function() {
$('<p><label for="parties"><input type="text" id="party_' + i +'" size="20" name="party" value="" placeholder="Party name" onkeyup="updateTxt(\'party_' + i +'\',\'txt' + i +'\');"/></label> Remove</p>').appendTo(partyDiv);
$('<p><span id="txt' + i +'"></span></p>').appendTo(textDiv);
i++;
return false;
});
$('#remParty').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
function updateTxt(field,toField){
var field = document.getElementById(field);
var toField = document.getElementById(toField);
toField.innerHTML=field.value;
}
When I've added a few fields the html looks like this:
<div id="partiesDiv">
<p>
<label for="parties"><input type="text" id="party" size="20" name="party"
value="" placeholder="Party name" onkeyup="updateTxt('party','txt');">
</label>
</p>
<p>
<label for="parties"><input type="text" id="party_2" size="20" name="party"
value="" placeholder="Party name" onkeyup="updateTxt('party','txt');">
</label> Remove <--- WHEN I CLICK HERE
</p>
</div>
<div id="text">
<p>
<span id="txt"></span>
</p>
<p>
<span id="txt2"></span>
</p> <--- I WANT THIS <p> TO BE REMOVED
</div>
What I'm guessing is that I should add a line below $(this).parents('p').remove(); that removes the p within div id="text". The problem is that I don't know how to make it know which p to remove.
I'm new to JavaScript and this might be over my head, so please let me know if I should clarify anything!
Thanks
You can remove the closest element to the parent element of your field by using this code:
$(this).parent.closest('p').remove();
Here is more you can read about 'closest' method http://api.jquery.com/closest/
My not so pretty solution:
$('#addParty').live('click', function() {
$('<p><label for="party"><input type="text" id="party_' + i +'" size="20"
name="party" value="" placeholder="Skriv partinamn"
onkeyup="updateTxt(\'party_' + i +'\',\'txt' + i +'\');"/></label>
<a href="#" *****class="remParty' + i +'"*****>Remove</a></p>')
.appendTo(partyDiv);
$('<p><span id="txt' + i +'"></span></p>').appendTo(textDiv);
i++;
return false;
});
So that the class="remParty" gets i appended to it for every new field that is created.
Then I just add
$('.remParty2').live('click', function() { $(this).parents('p').remove();
$("p:has(#txt2)").remove(); if(i==2){i--;} return false; });
as many times as I want the maximum number of parties allowed to be.
Dude, you have to update your jquery methods.
The .size() method is deprecated as of jQuery 1.8. Use the .length property instead.
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.
Use .closest() to call the closest parent, as the <p> tag you want.
Remember to use a class '.remParty' instead of an id '#remParty', because if you have more than one element with the same id it will not work.
Demo:
http://jsfiddle.net/EhjM7/
I rewrited it for you:
$(function() {
var i = $('#partiesDiv p').length + 1;
$(document).on('click','#addParty',function(e) {
e.preventDefault();
$('#partiesDiv').append('<p><label for="parties"><input type="text" id="party_' + i +'" size="20" name="party" value="" placeholder="Party name" onkeyup="updateTxt(\'party_' + i +'\',\'txt' + i +'\');"/></label> Remove</p>');
$('#text').append('<p><span id="txt' + i +'"></span></p>');
i++;
return false;
});
$(document).on('click','.remParty',function(){
$(this).closest('p').remove();
i--;
return false;
});
});
function updateTxt(field,toField){
var field = document.getElementById(field);
var toField = document.getElementById(toField);
toField.innerHTML=field.value;
}
First of all, you should NOT use the id attribute when you are using it more than once. there may be only one id with the same value within the page!
if you want to remove an upper element selecting it by its child you can use the :has() selector.
$("p:has(#txt2)").remove();
So lets begin again :)
$('#addParty').live('click', function() {
$('<p>Remove</p>').appendTo(partyDiv);
$('<p><span data-party-id="'+i+'"></span></p>').appendTo(textDiv);
});
I do assing data-party-id to both elements, as we can later easily refer to them.
Now lets do the magic to remove it.
$('.remParty').live('click', function() {
// learn something about data attributes and data()
var partyId = $(this).data("party-id");
$('p:has([data-party-id="' + partyId + '"])').remove();
});
But it would be much easier, if you would assign the identification to the p and not to the span. Then you do not need the :has() selector

Categories

Resources