jquery clone copying form elements twice on button click - javascript

I am using jquery clone.
When i click on add button a single clone is created with above fields...upto this clone works fine
But when i click Add button twice it create three copy of clone...it create three copies and like that..
i want when i create add button it just create only one clone every time and when i click remove it remove last clone...
below is my code..
<fieldset id="exercises">
<div class="exercise">
</div>
</fieldset>
<script>
$('#add_exercise').on('click', function() {
$("<div class='exercise address_box'><div class='box'></div></div>").appendTo('#exercises');
$("#toaddress").clone().val("").appendTo(".box");
$("#sender_name").clone().val("").appendTo(".box");
$("#OrderMobileCountryCode").clone().val("").appendTo(".box");
$("#sender_no").clone().val("").appendTo(".box");
$("#presentation").clone().val("").appendTo(".box");
$("<br><button type='button' class='orange_btn' id='add_exercise'>Remove</button>").appendTo('.box');
$("<br>").appendTo('.box');
$("<br>").appendTo('#exercises');
});
$('#exercises').on('click', '.orange_btn', function() {
$(this).closest(".exercise").remove();
});
</script>

Change id of dynamically added button from add_exercise to remove_exercise
$("<br><button type='button' class='orange_btn' id='remove_exercise'>Remove</button>").appendTo('.box');
And change the remove button event as ,
$('#exercises').on('click', '#remove_exercise', function() {
$(this).closest(".exercise").remove();
});
Because your code producing element with same id which in turn triggering events more than once.
Try this modified code,
<script>
$('#add_exercise').on('click', function() {
$("<div class='exercise address_box'><div class='box'></div></div>").appendTo('#exercises');
$("#toaddress").clone().val("").appendTo(".box");
$("#sender_name").clone().val("").appendTo(".box");
$("#OrderMobileCountryCode").clone().val("").appendTo(".box");
$("#sender_no").clone().val("").appendTo(".box");
$("#presentation").clone().val("").appendTo(".box");
$("<br><button type='button' class='orange_btn' id='remove_exercise'>Remove</button>").appendTo('.box');
$("<br>").appendTo('.box');
$("<br>").appendTo('#exercises');
});
$('#exercises').on('click', '#remove_exercise', function() {
$(this).closest(".exercise").remove();
});
</script>

You are using box class to append cloned item to your div. First time its work fine because there is only one div with box class, But in next click there are two div and so on.
Change your add button click listener like this
$('#add_exercise').on('click', function() {
var newDiv = $("<div class='exercise address_box'><div class='box'></div></div>").appendTo('#exercises');
var boxDiv = newDiv.find(".box");
$("#toaddress").clone().val("").appendTo(boxDiv);
$("#sender_name").clone().val("").appendTo(boxDiv);
$("#OrderMobileCountryCode").clone().val("").appendTo(boxDiv);
$("#sender_no").clone().val("").appendTo(boxDiv);
$("#presentation").clone().val("").appendTo(boxDiv);
$("<br><button type='button' class='orange_btn' id='add_exercise'>Remove</button>").appendTo(boxDiv);
$("<br>").appendTo(boxDiv);
$("<br>").appendTo('#exercises');
});
EDIT
I added a code snippet here it work fine. I use red boder for box class and black border for addres_box class.
$('#add_exercise').on('click', function() {
var newDiv = $("<div class='exercise address_box'><div class='box'></div></div>").appendTo('#exercises');
var boxDiv = newDiv.find(".box");
$("#toaddress").clone().val("").appendTo(boxDiv);
$("#sender_name").clone().val("").appendTo(boxDiv);
$("#OrderMobileCountryCode").clone().val("").appendTo(boxDiv);
$("#sender_no").clone().val("").appendTo(boxDiv);
$("#presentation").clone().val("").appendTo(boxDiv);
$("<br><button type='button' class='orange_btn' id='add_exercise'>Remove</button>").appendTo(boxDiv);
$("<br>").appendTo(boxDiv);
$("<br>").appendTo('#exercises');
});
$('#exercises').on('click', '.orange_btn', function() {
$(this).closest(".exercise").remove();
});
.address_box{
padding:10px;
border:1px solid #000;
}
.box{
border:1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="itemsto-clone">
<input id="toaddress" value="" name="sender_name">
<input id="sender_name" value="" name="sender_name">
<input id="OrderMobileCountryCode" value="" name="sender_name">
<input id="sender_no" value="" name="sender_name">
<input id="presentation" value="" name="presentation">
<div>
<fieldset id="exercises">
<div class="exercise">
</div>
</fieldset>
<button id="add_exercise">Add Exercise</button>

You create duplicate class name 'box' and you keep appendTo('.box')
So they just append it to all '.box' class
change your script to this
$('#add_exercise').on('click', function() {
$("<div class='exercise address_box'><div class='box'></div></div>").appendTo('.test');
var lastbox = $(".box").last();
$("#toaddress").clone().val("").appendTo(lastbox);
$("#sender_name").clone().val("").appendTo(lastbox);
$("#OrderMobileCountryCode").clone().val("").appendTo(lastbox);
$("#sender_no").clone().val("").appendTo(lastbox);
$("#presentation").clone().val("").appendTo(lastbox);
$("<br><button type='button' class='orange_btn' id='add_exercise'>Remove</button>").appendTo(lastbox);
$("<br>").appendTo(lastbox);
$("<br>").appendTo('#exercises');
});
$('#exercises').on('click', '.orange_btn', function() {
$(this).closest(".exercise").remove();
});

Since question is not very clear, here is the way to implement your requirement of cloning elements.
var counter = (function(){
var counter = 1;
return function(){
return counter++;
}
})();
$('#add_exercise').on('click', function() {
var clone = $('#exercises div.exercise:eq(0)').clone();
clone.find('[id]').each(function(i,c){
$(c).attr('id', $(c).attr('id') + counter());
$(c).attr('placeholder', $(c).attr('id'));
});
$('#exercises').append(clone)
});
$('#remove_exercise').on('click', function() {
if($('#exercises div.exercise').length !=1)
$('#exercises div.exercise:last').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<button id="add_exercise">Add</button>
<button id="remove_exercise">Remove</button>
</div>
<div id="exercises">
<div class="exercise">
<input id="myId" placeholder="my id" />
<input placeholder="input with no id" />
</div>
</div>

Related

Unable to delete row using jquery which was dynamically created

I am creating new rows using jquery and want to delete that row when delete button is pressed. Adding new row part is working fine and the problem is in delete part. When I click on delete button then nothing happens. It doesn't even show alert which is written in code. It seems to me like delete button is not even getting pressed.
How can I delete that particular record when delete button is pressed?
JSfiddle is given below
https://jsfiddle.net/ec2drjLo/
<div class="row">
<div>
Currency: <input type="text" id="currencyMain">
</div>
<div>
Amount: <input type="text" id="amountMain">
</div>
<div>
<button id="addAccount">Add Account</button>
</div>
</div>
<div id="transactionRow">
</div>
As you have added the elements as a string, they are not valid HTML elements and that's why you can't add an event listener. You can add the click event to the document body and capture the event target, like
$(document).on('click', function (e){
if(e.target.className === 'deleteClass'){
//process next steps
}
}
You can try the demo below, not sure if it's the result you need, but the delete button works. Hope it helps!
let accountCount = 0;
$("#addAccount").click(function (e)
{
accountCount++;
let mystring = "<label class=\"ok\" id=\"[ID]\">[value]</label>";
let deleteString = "<button class=\"deleteClass\" id=\"deleteAccount"+ accountCount +"\">Delete Account</button>";
let currency = mystring.replace("[ID]", "currency"+ accountCount).replace("[value]", $("#currencyMain").val());
let amount = mystring.replace("[ID]", "amount"+ accountCount).replace("[value]", $("#amountMain").val());
$("#transactionRow").append(currency);
$("#transactionRow").append(amount);
let div = document.createElement('div');
div.innerHTML =deleteString;
$("#transactionRow").append(div);
$("#currencyMain").val('');
$("#amountMain").val('')
});
$(document).on('click', function (e)
{
if(e.target.className === 'deleteClass'){
var content = $("#transactionRow").html();
var pos = content.lastIndexOf("<label class=\"ok");
if(pos > 5)
$("#transactionRow").html(content.substring(0,pos));
else
alert("You cannot delete this row as at least one Account must be present");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="row">
<div>
Currency: <input type="text" id="currencyMain">
</div>
<div>
Amount: <input type="text" id="amountMain">
</div>
<div>
<button id="addAccount">Add Account</button>
</div>
</div>
<div id="transactionRow" style="border: 1px solid grey">
</div>

how remove the text box one bye one in button click

HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="plusicondiv" class="plusicon" src="vectorimages/pluseicon.svg" />
<div id="plusicondivbox"class="insidediv " style="margin-top:-53px;" >
<img class="mynasicondiv" src="vectorimages/mynas.svg" />
JS
$(function () {
$('.plusicon').on('click', function () {
var textBox = '<input type="text" class="textbox"/>';
var a = $(this).attr("id")
$('#'+a+"box").append(textBox);
var img = '<img class="mynasicondiv" src="vectorimages/mynas.svg"></img>';
$('#' + a + "box").append(img);
$(function () {
$(document).on("click", ".mynasicondiv", function () {
$(this).parent('#' + a + "box").empty();
return
})
});
});
I have two buttons, plusicon button and mynesicon button. I want click the plusicon button add the textbox and image,also clicking the mynessicon button should remove the textboxs and images. My problem is that clicking the mynesicon corresponding textbox is only removing.
Use .each to remove all the elements and in order to remove use the .remove function on the targeted element.
$(function () {
var a;
$('.plusicon').on('click', function () {
var textBox = '<input type="text" class="textbox"/>';
a = $(this).attr("id")
console.log(a);
$('#'+a+"box").append(textBox);
var img = '<img class="mynasicondiv" src="vectorimages/mynas.svg"></img>';
$('#' + a + "box").append(img);
});
$('.mynasicondiv').on("click", function () {
$('#' + a + "box").each(function(index, v){
$(v).remove();
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div><img id="plusicondiv" class="plusicon" src="vectorimages/pluseicon.svg" /></div>
<div><img class="mynasicondiv" src="vectorimages/mynas.svg" /> </div>
<div id="plusicondivbox"class="insidediv " ></div>
</div>

is it possible to hide div when another button is click?

I am trying to hide the div's when different buttons are clicked but I don't know how to. (So when 'Test 1' is clicked it should hide 'Test 2' Div and vice versa) I checked here and on Google but couldn't find an answer for it.
Javascript :
function showHide(divId) {
var theDiv = document.getElementById(divId);
if (theDiv.style.display == "none") {
theDiv.style.display = "";
} else {
theDiv.style.display = "none";
}
}
HTML :
<input type="button" onclick="showHide('hidethis')" value="Test It">
<div id="hidethis" style="display:none">
<h1>TEST ME!</h1>>
</div>
<input type="button" onclick="showHide('hidethis2')" value="Test It 2">
<div id="hidethis2" style="display:none">
<h1>TEST MEEEEEEEEEEEEEEE 2!</h1>
</div>
JSFIDDLE: is not doing it here but works locallyhttp://jsfiddle.net/S5JzK/
<input type="button" onclick="showHide('hidethis')" value="Test It" />
<div id="hidethis" style="display:none">
<h1>TEST ME!</h1>
</div>
<input type="button" onclick="showHide('hidethis2')" value="Test It 2">
<div id="hidethis2" style="display:none">
<h1>TEST MEEEEEEEEEEEEEEE 2!</h1>
</div>
function showHide(divId) {
$("#"+divId).toggle();
}
Check the Fiddle http://jsfiddle.net/S5JzK/7/
Please try this, it works well and so simple,
<html>
<head>
<style>
.manageDiv{
display:none;
}
</style>
</head>
<body>
<input type="button" class="testButton" value="Test It" />
<input type="button" class="testButton" value="Test It 2" />
<div id="hidethis2" class="manageDiv">
<h1>TEST MEEEEEEEEEEEEEEE 2!</h1>
</div>
</body>
</html>
$(function(){
$(".testButton").on("click", function(){
$("#hidethis2").toggleClass("manageDiv");
});
});
To it work in fiddle, in your example, you need to select (No wrap - in head) on the left.
Look the example below, using pure javascript:
HTML
<input type="button" onclick="showHide('hidethis')" value="Test It">
<div id="hidethis" style="display:none">
<h1>TEST ME!</h1>
</div>
<input type="button" onclick="showHide('hidethis2')" value="Test It 2">
<div id="hidethis2" style="display:none">
<h1>TEST MEEEEEEEEEEEEEEE 2!</h1>
</div>
JAVASCRIPT
function showHide(divId) {
/* Hide all divs */
var elements = document.getElementsByTagName('div');
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = "none";
}
/* Set display */
var theDiv = document.getElementById(divId);
theDiv.style.display = "";
}
http://jsfiddle.net/S5JzK/9/
ANOTHER JAVASCRIPT EXAMPLE
function showHide(divId) {
/* Hide the divs that you want */
var div1 = document.getElementById('#hidethis');
var div2 = document.getElementById('#hidethis2');
div1.style.display = "none";
div2.style.display = "none";
/* Set display */
var theDiv = document.getElementById(divId);
theDiv.style.display = "";
}
Using JQuery:
function showHideDiv(divId, bShow) {
if (bShow) {
$("#" + divId).show();
} else {
$("#" + divId).hide();
}
}
your code seems fine. are you sure you enter the function upon click? try adding a breakpoint using developer tools or an alert.
Anyways, I see you tagged this post with jquery. you can you it to do the task more elegantly.
$("#" + theDiv).hide();
or for showing it:
$("#" + theDiv).show();
"JSFIDDLE: is not doing it here but works locally"
Yes, because by default jsfiddle wraps your JS in an onload handler, which means the function declaration is local to that handler. Inline html attribute event handlers like your onclick="showHide('hidethis')" can only call global functions.
Under jsfiddle's Frameworks & Extensions heading there's a drop-down where you can change the default "onload" to "No wrap - in head" (or "No wrap - in body"). That'll make your function declaration global as in your local implementation.
Demo: http://jsfiddle.net/S5JzK/8/

Javascript: Change Div size on button click

<script type="text/javascript">
var button = document.getElementById("button");
var idTab5 = document.getElementById("idTab5");
var button2 = document.getElementById("button2");
function showwMore() {
button.style.display="none";
idTab5.style="overflow:hidden;display:block;height:100%;font-size:12px;line-height:14px;";
button2.style.display="block";
}
function showwLess() {
button2.style.display="none";
idTab5.style="overflow:hidden;height:250px;font-size:12px;line-height:14px;";
button.style.display="block";
}
</script>
and this is the other code:
{if $product->description|count_characters:true > 350 }
{* full description *}
<div id="idTab5" style="overflow:hidden;height:250px;font-size:12px;line-height:14px;">{$product->description}</div>
<input id="button" type="button" style="margin-top:5px;font-size:12px;color:white; width:120px;background:#4e3248;border:none;height:30px;border-radius:5px;" value="Mostrar +" onclick="showwMore()">
<input id="button2" type="button" style="margin-top:5px;display:none;font-size:12px;color:white; width:120px;background:#4e3248;border:none;height:30px;border-radius:5px;" value="Mostrar -" onclick="showwLess()">
{else}
<div id="idTab5" style="overflow:hidden;height:250px;font-size:12px;line-height:14px;">{$product->description}</div>
{/if}
now its seems fine to me, but onclick, the div isnt growing, any idea why is this happening? ive checked the code many times cant find out why it isnt working, did i miss something???
For use multiple styles by javascript you can use setAttribute() like
should be
idTab5.setAttribute("style", "overflow:hidden;display:block;height:100%;font-size:12px;line-height:14px;");
Or
you can use cssText property to use css as string on element
idTab5.style.cssText = "overflow:hidden;display:block;height:100%;font-size:40px;line-height:14px;";
instead of
idTab5.style="overflow:hidden;display:block;height:100%;font-size:12px;line-height:14px;";
HTML:
<div id="idTab5" style="height:250px;font-size:12px;line-height:14px; border:1px solid black;"></div>
<input id="button" type="button" style="margin-top:5px;font-size:12px;color:black; width:120px;background:#4e3248;border:none;height:30px;border-radius:5px;" value="Mostrar +" onclick="showwMore()">
<input id="button2" type="button" style="display:none;margin-top:5px;display:block;font-size:12px;color:white; width:120px;background:#4e3248;border:none;height:30px;border-radius:5px;" value="Mostrar -" onclick="showwLess()">
JAVASCRIPT:
var button = document.getElementById("button");
var idTab5 = document.getElementById("idTab5");
var button2 = document.getElementById("button2");
function showwMore() {
button.style.display="none";
idTab5.style="display:block;height:100%;font-size:12px;line-height:14px; border:1px solid black;";
button2.style.display="block";
}
function showwLess() {
button2.style.display="none";
idTab5.style="height:250px;font-size:12px;line-height:14px; border:1px solid black;";
button.style.display="block";
}
see FIDDLE

Pass js var into html block being added via appendTo

I've got this html which i'm injecting into the page when someone clicks a button. The html gets appended again each time the button is clicked using the js below.
<div style="display: none;">
<div class="grab-me">
<p>This is fieldset 1</p>
<input name="foo[]" />
<input name="bar[]" />
<input name="oth[]" />
</div>
</div>
var count = 1;
$(function(){
$('.add-member').live("click", function(e){
e.preventDefault(e);
count += 1;
var grab = $('.grab-me')
.clone()
.removeClass('grab-me')
.appendTo('#register');
});
});
But what i need to do is where it says "This is fieldset 1" i need to increase that number by 1 each time so subsequent appends say This is fieldset 2, This is fieldset 3 etc etc. I can't see how i can pass a variable (my count var) in to the html block when it gets cloned that will replace that number.
Here is a jsfiddle of it: http://jsfiddle.net/tzbgA/
Any help would be great! Thanks!!
you can give the sentence you want to change class. Then using jQuery selectors change the text inside it.
<body>
<button class="add-member">add more</button>
<div style="display: none;">
<div class="grab-me">
<p class="count">This is fieldset 1</p>
<input name="foo[]" />
<input name="bar[]" />
<input name="oth[]" />
</div>
</div>
<div id="register">
</div>
</body>
var count = 1;
$(function(){
$('.add-member').on("click", function(e){
e.preventDefault(e);
var grab = $('.grab-me')
.clone()
.removeClass('grab-me')
.appendTo('#register')
.find('p.count').html('This is fieldset '+count);
count += 1;
});
});
add span:
<p>This is fieldset <span>1</span></p>
var count = 1;
$(function(){
$('.add-member').on("click", function(e){
e.preventDefault(e);
count += 1;
var grab = $('.grab-me')
.clone()
.removeClass('grab-me')
.appendTo('#register');
$('.span').html('count');
});
});
var count = 1;
$(function(){
$('.add-member').live("click", function(e){
e.preventDefault(e);
count += 1;
var grab = $('.grab-me').clone();
$(grab p).html('This is fieldset '+count).appendTo('#register');
});
});
Fiddle: http://jsfiddle.net/howderek/tzbgA/2/
Here's a version that uses 8 lines of code:
Code (Javascript)
var count = 1,
html = ' <p>This is fieldset #</p><input name="foo[]"/> <input name = "bar[]"/> <input name = "oth[]"/>';
$(function () {
$('.add-member').live("click", function (e) {
e.preventDefault(e);
document.getElementById("register").innerHTML += html.replace("#",++count);
});
});

Categories

Resources