Add one div at a time, or delete duplicates fields - javascript

I have a part of a project I'm working on in which I have to add repeated instances of the same div. It mostly works, however, instead of adding individual instances, the previous div added seems to be repeating itself, rather than having the "original div" adding.
Here is the jsfiddle together with the code I'm using so far:
<div class="shape" id="plan4_shape">
<span class="bakkant">
<input class="measures" id="plan4_width" placeholder="mm" name="p4width" value="w1"/>
<span class="times"> ×</span>
<input class="measures" id="plan4_width" placeholder="mm" name="p4length" value="l1" />
</span>
<script id="template" type="text/template">
<span class="bakkant" id="bakkant">
<input class="measures" id="plan4_width" placeholder="mm" name="p4width" value="w"/>
<span class="times"> ×</span>
<input class="measures" id="plan4_width" placeholder="mm" name="p4length" value="l" />
<button class="close" id="close">×</button>
</span>
</script>
<button type="button" name="add_row" class="addrow" id="addrow4" onClick="addrow()">Add row</button>
<textarea name="more_info" id="profiles" placeholder="Beskriv fritt, vilka kanter du vill få profilerade."></textarea>
</div>
jQuery code
$(function() {
var i = 0;
$('#addrow4').click(function() {
var $clone = $($('#template').html());
$clone.attr('id', "bakkant" + ++i);
$clone.find('p').attr("Bob" + ++i)
$clone.find('input').attr('value', "l" + ++i);
$clone.find('input').attr('value', "w" + ++i);
$('.bakkant').append($clone);
});
$('.shape').on('click', '.close', function() {
$(this).closest('.bakkant').remove();
});
});

As you need to add the new row at the last, you need to do
$('.bakkant').last().append($clone);
You need not do ++i for changing every id or value attribute, just increment it once for each event.
Working Fiddle here.

Related

jQuery onclick does not change HTML input

When I click the zero button, I expect the the function zero to change the input to zero, but it seems to be not working. Is there anyway to do this in JavaScript instead of jQuery?
HTML
<div class="display" id="out">test</div>
<div class="form-group">
<label for="comment">value:</label>
<input class="form-control" type="text" value="0.00" id="in"></input>
</div>
<button id="zero" onclick="setzero()">
<span class="glyphicon glyphicon-fire"></span> Zero
</button>
jQuery
$('#in').on("change", function(){
$('#out').html($(this).val());
});
function setzero() {
$('#in').val(0);
}
http://jsfiddle.net/ahpu8wwx/12/
try you updated I have updated adding a new variable sum
var sum = 0;
$('#in').on("change", function(){
sum += parseInt($(this).val());
$('#out').html(sum);
setzero();
});
function setzero() {
$('#in').val(0);
}
Demo
Tushar needs to put his comment to the answer:
You code is correct, but you run it in a wrong context in fiddle, you need to set "No Wrap" option like
The onlick is not working because the the function setzero() is not in global context so you need to move it outside the document ready handler
You can use click() event handler and trigger change event using cahnge()
$('#in').on("change", function() {
$('#out').html($(this).val());
});
$('#zero').click(function() {
$('#in').val(0).change();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="display" id="out">test</div>
<div class="form-group">
<label for="comment">value:</label>
<input class="form-control" type="text" value="0.00" id="in">
</div>
<button id="zero">
<span class="glyphicon glyphicon-fire"></span> Zero
</button>
Update : Or you need to define the function outside the $(document).ready(function(){..}); handler
$(document).ready(function() {
$('#in').on("change", function() {
$('#out').html($(this).val());
});
});
function setzero() {
$('#in').val(0).change();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="display" id="out">test</div>
<div class="form-group">
<label for="comment">value:</label>
<input class="form-control" type="text" value="0.00" id="in">
</div>
<button id="zero" onclick="setzero(this)">
<span class="glyphicon glyphicon-fire"></span> Zero
</button>
I think it is better to use jquery events, using it for the click is working
$('#zero').on('click', function(e){
$('#in').val(0);
e.preventDefault();
});

How do I repeat the piece of html code 10 times by clicking on the same button using JS/Jquery?

I want to be able to display the same piece of html code 10 times under the div called: <div id="add_remove_product_name"> By clicking on the button called: <button id="add_another_product_name">. I think I need some kind of a for loop for the job but are not sure. Any suggestion will be helpful, thanks.
My HTML code:
<div id="product_name">
<input id="skriv_produktnavn" placeholder="Skriv Produktnavn her" required></label>
<button id="add_another_product_name">Tilføj endnu et produktnavn</button>
<div id="add_remove_product_name">
<input id="added_product_name" placeholder="Skriv Produktnavn her" required></label>
<button id="remove_product_name">X</button>
</div>
Use a for loop to concatenate 10 copies of the HTML code. Then use .after() to put this after the DIV.
$("#add_another_product_name").click(function() {
var html = '';
for (var i = 0; i < 10; i++) {
html += 'html code that you want to repeat';
}
$("#add_remove_product_name").after(html);
}
You can use jQuery clone() however when cloning an element all the attributes will be the same. Fo example they will all have the same id attribute which will cause problems and it is not valid html
So in order to do the clone correctly you have fix the cloned element
DEMO: http://jsfiddle.net/rpyt445e/
var $tpl = $('#product_name').clone();
var num = 0
$('#clone').click(function () {
num++;
var $cloned = $tpl.clone();
$cloned.attr('id', $tpl.attr('id') + '_' + num);
$(':not([id=""])', $cloned).each(function(){
$(this).attr('id', $(this).attr('id') + '_'+num);
});
$cloned.appendTo('#wrapper');
});
HTML:
<div id="wrapper">
<div id="product_name">
<input id="skriv_produktnavn" placeholder="Skriv Produktnavn her" required />
<button id="add_another_product_name">Tilføj endnu et produktnavn</button>
<div id="add_remove_product_name">
<input id="added_product_name" placeholder="Skriv Produktnavn her" required />
<button id="remove_product_name">X</button>
</div>
</div>
</div>
<button id="clone">Clone</button>
A technique for adding the additional elements without having to create ugly strings of html in the JavaScript is to start with one hidden set of the elements in the html. At page load time, you remove that set, but keep a reference to it. Then when you want to add a set to the page, you clone the set you removed. All of this is easier if you add a container div around the additional inputs.
You also need to make sure id attribute values are unique. In the case of the remove buttons, you can replace the id with a class. As for the input id values, if you really need them, you can add an index value to them.
Since the remove buttons are dynamically added, I suggest using event delegation when binding the click-handler.
HTML:
<div id="product_name">
<input id="skriv_produktnavn" placeholder="Skriv Produktnavn her" required="required"/>
<button id="add_another_product_name">Tilføj endnu et produktnavn</button>
<div id="additional_product_names">
<div class="add_remove_product_name" style="display: none;">
<input id="added_product_name" placeholder="Skriv Produktnavn her" required="required"/>
<button class="remove_product_name">X</button>
</div>
</div>
</div>
JavaScript:
$(function() {
var MAX = 10;
var $addBtn = $('#add_another_product_name'),
$additionalContainer = $('#additional_product_names');
$TEMPLATE = $additionalContainer.children(':first').remove();
function update() {
var $additonalDivs = $additionalContainer.children();
// Enable/disable the add button.
$addBtn.prop('disabled', $additonalDivs.length >= MAX);
// Re-index the "id" attributes.
$additonalDivs.find('input').attr('id', function(i) {
return 'added_product_name[' + i + ']';
});
}
$addBtn.click(function() {
$TEMPLATE.clone().appendTo($additionalContainer).show();
update();
});
$('#product_name').on('click', '.remove_product_name', function() {
$(this).closest('.add_remove_product_name').remove();
update();
});
});
jsfiddle

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.

Replace text on button click

I'm looking for some code that will allow me to click a button (Button with value "Next") which will then replace some of the code I have on my page with new code. This is my current code, I need to replace everything after the score counter. Apologies for the sloppy code, I'm pretty new to this.
<body>
<p>Score: <span id="counter">0</span></p><br/>
<p>1) What colour is this?</p><br />
<p><img style= "margin: 0 auto;" src="colour1.png" width="70%"></p><br /><br />
<p><button id="none" onClick="showDiv01()">Almond White</button><br>
<button id="score" onClick="showDiv02(); this.disabled = 'true';">Raspberry Diva</button><br>
<button id="none" onClick="showDiv01()">Melon Sorbet</button><br>
<button id="none" onClick="showDiv01()">Gentle Lavender</button><br></p>
<div id="answer1" style="display:none;" class="wronganswer">✗</div>
<div id="answer2" style="display:none;" class="rightanswer">✓</div>
<p><input type="button" name="next2" value="Next" onClick="showDiv2()" /></p>
</body>
try the below fiddle i am not sure its perfect u want or not but just tried
<body>
<p>Score: <span id="counter">0</span></p><br/>
<div id="div1">
<p>1) What colour is this?</p><br />
<p><img style= "margin: 0 auto;" src="colour1.png" width="70%"></p><br /><br />
<p><button id="none" onClick="showDiv01()">Almond White</button><br>
<button id="score" onClick="showDiv02(); this.disabled = 'true';">Raspberry Diva</button><br>
<button id="none" onClick="showDiv01()">Melon Sorbet</button><br>
<button id="none" onClick="showDiv01()">Gentle Lavender</button><br></p>
</div>
<div id="div2" hidden>
1) What car is this?</p><br />
<p><img style= "margin: 0 auto;" src="colour1.png" width="70%"></p><br /><br />
<p><button id="none" onClick="showDiv01()">abc</button><br>
<button id="score" onClick="showDiv02(); this.disabled = 'true';">def</button><br>
<button id="none" onClick="showDiv01()">rtrt</button><br>
<button id="none" onClick="showDiv01()">xyz</button><br></p>
</div>
<div id="answer1" style="display:none;" class="wronganswer">✗</div>
<div id="answer2" style="display:none;" class="rightanswer">✓</div>
<p><input type="button" id="btn" name="next2" value="Next" onClick="showDiv2()" /></p>
</body>
$('#btn').click( function() {
$("#div1").hide();
$("#div2").show();
});
http://jsfiddle.net/uxyQG/
If you want to replace the text on button click. I checked you button have an onClick="showDiv2()"
So try like this (for an example)
function showDiv2 () {
document.getElementById('counter').innerHTML = ""; //empty the value
}
Here is example fiddle, I have create when you click next the counter will be replaced.
What you want to do here is place all the content you want to replace inside a <div>.
then you will want to give that div an id attribute.
e.g.
<div id="yourID">
HTML CONTENT HERE
</div>
Then in javascript, you would need to create a function that would fire on an onclick event.
Markup:
<input type="button" onclick="changeContent('yourID', '<div>OtherHTML</div>')" value="NEXT" />
when you have these 2 components, you will want to make a script that will execute your function.
<script type="text/javascript">
function changeContent(id, html) {
//Get the element that needs it's contents replaced.
var container = document.getElementById(id);
//insert new HTML onclick.
container.innerHTML = html;
}
</script>
This is a simple example of what you need.
You could externalize this javascript in a seperate file.
If you want to do this, you will need to include the script in the <head> of your html document.
<script type="text/javascript" src="path/to/js.js"></script>
Because this will load before any of the DOM will have been loaded, you will get errors.
To solve this, the new contents of the file will be:
js.js
window.onload = function() {
function changeContent(id, html) {
//Get the element that needs it's contents replaced.
var container = document.getElementById(id);
//insert new HTML onclick.
container.innerHTML = html;
}
}
This should work for you in this scenario.
Hope this helped
&dash; Sid

Adding and removing dom sections with javascript

I want to be able to add new sections (via the 'add' link) and remove them (via the 'x' button) like seen in the image.
The HTML for the image:
<fieldset>
<legend>Legend</legend>
<div id="section0">
<input type="text" name="text1" value="Text1" />
<input type="text" name="text2" value="Text2" size='40' />
<input type="button" value="x" style="width: 26px" /><br />
</div>
add<br />
</fieldset>
I guess I could add new sections as needed (i.e. section1, section2) and delete those sections according to which button was pressed. There would be a javascript function that would inject sections in the DOM everytime the 'add' link was clicked and another for deleting a section everytime the 'x' button was clicked.
Since I have so little experience in HTML and Javascript I have no idea if this is a good/bad solution. So, my question is exactly that: Is this the right way to do it or is there a simpler/better one? Thanks.
P.S.: Feel free to answer with some sample code
Here's one way to do it:
<script type="text/javascript">
function newrow() {
document.getElementById("customTable").innerHTML += "<tr><td><input type='text'></td><td><input type='text'></td><td><button onclick='del(this)'>X</button></td></tr>";
}
function del(field) {
field.parentNode.parentNode.outerHTML = "";
}
</script>
<body onload="newrow()">
<fieldset>
<legend>Legend</legend>
<table>
<tbody id="customTable">
</tbody>
</table>
<button onclick="newrow()">Add</button>
</fieldset>
</body>
You could add IDs to them if you wanted, or you could call them by their position document.getElementsByTagName("input")[x].value The inputs would start at 0, so the left one is 0, right is 1, add row: left is 2, right is 3, etc.
If you delete one, the sequence isn't messed up (it re-evaluates each time), which is better than hard-coded IDs.
I just answered a nearly identical question only a few minutes ago here using jQuery: https://stackoverflow.com/a/10038635/816620 if you want to see how it worked there.
If you want plain javascript, that can be done like this.
HTML:
<div id="section0">
<input type="text" name="text1" value="Text1" />
<input type="text" name="text2" value="Text2" size='40' />
<input type="button" value="x" style="width: 26px" /><br />
</div>
add<br />
Javascript:
function addSection(where) {
var main = document.getElementById("section0");
var cntr = (main.datacntr || 0) + 1;
main.datacntr = cntr;
var clone = main.cloneNode(true);
clone.id = "section" + cntr;
where.parentNode.insertBefore(clone, where);
}​
Working demo: http://jsfiddle.net/jfriend00/TaNFz/
http://pastebin.com/QBMEJ2pq is a slightly longer but robust answer.

Categories

Resources