Append increasing number on click - javascript

I'm trying to append an increasing number to elements on click. I can't seem to make it work.
My code:
$('#on').click(function() {
$("b").click(function(e) {
var numCount = ($("[span class='num'>").length + 1);
var element = $("<span class='num'>" + numCount + "'>" + numCount + "</span>");
$(this).append(element);
});
});
I think It's a simple syntax error in my code, but I'm learning here so I could be completely wrong. It's important for the class to be added too.
Here's a Fiddle

Change
var numCount = ($("[span class='num'>").length + 1);
to
var numCount = ($(".num").length + 1);
You need to find .num elements, not create new ones.
In addition, your element line doesn't create valid HTML either. Try the following:
var element = $("<span class='num'>" + numCount + "</span>");

Related

Find the last element that has appeared DOM html

I have a code that puts images on a table(html), and I want to focus on the image that has just appeared.
I know that i have to use $(this) but i don't know how, here is my code
function positioning(year, mon) {
$('#' + year + ' .' + mon).prepend('<img class="black_point" src="./images/circle.png"/>');//that adds the image
var table = document.getElementById("table");
var images = table.getElementsByTagName("img");
//here I need the current image I had just add to send to that function
function connect(images) {
var tabBcr = table.getBoundingClientRect();
var imgBcr = image.getBoundingClientRect();
x = imgBcr.left + (imgBcr.width / 2) - tabBcr.left;
y = imgBcr.top + (imgBcr.height / 2) - tabBcr.top;
}
}
I hope I have explained well .
I think it will work, add this where you want to get that img element:
var imgelem=$('#' + year + ' .' + mon).find("img:first");

Clone DIV and its contents with new ids [duplicate]

This question already has answers here:
Clone <div> and change id
(4 answers)
Closed 9 years ago.
I'm trying to clone a div and the input elements inside it. When I clone it, I would like all the ids to increment by one. I've made a fiddle to show you what I'm doing.
$("#add").click(function (e) {
var amount = $('div.classes').length;
var new_amount = amount + 1;
var cloned_div = $('#class-' + amount);
$(cloned_div).clone().attr('id', 'class-' + new_amount).insertAfter('#class-' + amount);
});
jsFiddle
So far I've cloned the whole div itself and the ids increment but the elements inside remain the same. How would I get all elements inside the div to increment by one?
You have cloned the entire div without modifying it's contents. Try something like:
$("#add").click(function (e) {
var amount = $('div.classes').length;
var new_amount = amount + 1;
var cloned_div = $('#class-' + amount);
$(cloned_div).clone().attr('id', 'class-' + new_amount).insertAfter('#class-' + amount).find('input').each(function (i, e) {
$(e).attr('id', $(e).attr('id').replace(amount, new_amount));
});
});
DEMO
You can recursively replace all id's using find / replace:
$("#add").click(function (e) {
var amount = $('div.classes').length;
var new_amount = amount + 1;
var cloned_div = $('#class-' + amount).clone();
cloned_div.insertAfter('#class-' + amount);
cloned_div.find('[id$="-' + amount + '"]').andSelf().each(function(index, child) {
child.id = child.id.replace("-" + amount, "-" + new_amount);
});
});
See jsFiddle
cloned_div.find('[id$="-' + amount + '"]') will search for all child elements having an id attribute ending on "-" + amount, .andSelf() will include the cloned div as you want to change the id there also. Then simply replace the number part in the id of each child (and self).
Try adding this:
$('#class-' + new_amount + ' input:nth-child(1)').attr('id', 'name-class-' + new_amount);
$('#class-' + new_amount + ' input:nth-child(2)').attr('id', 'number-class-' + new_amount);
$('#class-' + new_amount + ' input:nth-child(3)').attr('id', 'book-class-' + new_amount);
just below your $(cloned_div).clone() statement.
See it in action:
http://jsfiddle.net/ZHHcA/1/
These other answers are close, but the problem with their solutions is the original ID prefixes are being lost: number-class-1 is becoming class-1 which is not ideal.
Here is a better option:
$("#add").click(function (e) {
var amount = $('div.classes').length;
var new_amount = amount + 1;
var cloned_div = $('#class-' + amount);
var $cloned = $(cloned_div).clone().attr('id', 'class-' + new_amount).insertAfter('#class-' + amount);
$cloned.children().each(function(){
var $child = $(this);
var oldID = $child.attr('id');
var newID = oldID.replace(/[0-9]+$/, new_amount); // replace just the number, leave the rest of the ID name in tact
$child.attr('id', newID);
})
});
And a working example

remove array using jquery

I have created nestled arrays, which I then append to a div. When i click the button with id "name", a movie with title is stored in an array $titelBetyg, which is later stored in another array $films. Whenever i create a new $titelBetyg, i want to remove the previous $films from my div, before replacing it with the new one. How do I do this?
Javascript
$(document).ready(function(){
var $films = [];
$('#name').keyup(function(){
$('#name').css('background-color', 'white');
});
$('#options').change(function(){
$('#options').css('background-color', 'white');
});
$("#button").click(function(){
var $titelBetyg = [];
var $titel = $('#name').val();
var $betyg = $('#options').val();
if($titel == ""){
$('#name').css('background-color', 'red');
alert("Fail");
}
else if($betyg == "0"){
$('#options').css('background-color', 'red');
alert("Fail");
}
else{
$titelBetyg.push($titel);
$titelBetyg.push($betyg);
$films.push($titelBetyg);
// here is where i need to remove it before appending the new one
$('#rightbar').append("<ul>");
for(i=0; i<$films.length; i++){
$('#rightbar').append("<li>" + $films[i][0] + " " + $films[i][1] + "</li>" + "<br>");
}
$('#rightbar').append("</ul>");
}
});
$('#stigande').click(function(a,b){
});
$('#fallande').click(function(){
});
});
Use .empty() like this (and append to the <ul> instead of something else):
var $ul = $("<ul>");
for (var i=0; i<$films.length; i++) {
$ul.append("<li>" + $films[i][0] + " " + $films[i][1] + "</li><br>");
}
$('#rightbar').empty().append($ul);
Btw, it might be easier to only append the new one instead of emptying and rebuilding the whole thing:
$('#rightbar ul').append("<li>" + $titel + " " + $betyg + "</li><br>");
To remove only the list contents (and nothing else) from the #rightbar, you could use this:
var $ul = $('#rightbar ul').empty();
if (!$ul.length) // if nonexistent…
$ul = $("<ul>").appendTo('#rightbar'); // create new one
for (var i=0; i<$films.length; i++)
$ul.append("<li>" + $films[i][0] + " " + $films[i][1] + "</li>");
document.getElementById('rightbar').innerHTML = '';
That way rightbar is totally empty.
You only require to remove the content of the container. So, use the .empty() function
$('#rightbar').empty().append("<ul>"); //It will empty the content and then append
for(i=0; i<$films.length; i++){
$('#rightbar').append("<li>" + $films[i][0] + " " + $films[i][1] + "</li>" + "<br>");
}
$('#rightbar').append("</ul>");

Is it possible to use cloneNode to clone multiple divs?

I'm trying to clone to divs in and append them to to other divs (their parents). I'm using clonenode for this but it doesn't seem to work. It clones the div in the first function and appends it to the parent of the div in the second function! Not sure what I'm doing wrong.
Here's the code (*EDIT:*var added):
function cloneQ() {
//Cloning questions and shit
cloneQ.id = (cloneQ.id || 0) + 1;
var question = document.getElementById("question");
var clone = question.cloneNode(true);
var numberOfQuestions = $('.question').length;
var id = "questioncon" + cloneQ.id;
clone.id = id;
question.parentNode.appendChild(clone);
var inid = "question" + cloneQ.id;
var optionid = "optionsdiv" + cloneQ.id;
$('#' + id + ' ' + '.' + 'questionin').attr('id', inid);
$('#' + id + ' ' + '.' + 'options').attr('id', optionid);
$('#' + id + ' h2').html('Question ' + cloneQ.id);
//Question Cloned
}
function cloneforPrint() {
cloneforPrint.id = (cloneforPrint.id || 0) + 1;
var questionprint = document.getElementById("questionprint");
var cloneprint = questionprint.cloneNode(true);
var printid = "questionprint" + cloneforPrint.id;
cloneprint.id = printid;
questionprint.parentNode.appendChild(clone);
var printinid = "thequestionprint" + cloneforPrint.id;
$('#' + printid + ' ' + '.' + 'thequestionprint').attr('id', printinid);
}
LIVE here: http://bit.ly/R8hB2m
Edit : Global vars are the problem.
You aren't putting var in front of your variables, making them global. The cloneForPrint function is picking up vars defined in cloneQ.
Init all the variables properly and you'll get some errors indicating where the problems are.
CloneQ is indeed appending to questions parent, but cloneForPrint then moves it somewhere else.
-- Old answer --
There's not enough here to work out what the problem is. My 1st guess is that the question element has the same parent as the questionprint element.
Based on the code given, cloneQ should definitely append to questions parent. So to give the appearance you've specified the DOM probably doesn't look like what you expect.

JQuery: get a child as you append it

I am appending p tags to a div as I process a json request and would liek to style it according to what is in the request.
$(document).ready(function() {
function populatePage() {
var numberOfEntries = 0;
var total = 0;
var retrieveVal = "http://www.reddit.com/" + $("#addressBox").val() + ".json";
$("#redditbox").children().remove();
$.getJSON(retrieveVal, function (json) {
$.each(json.data.children, function () {
title = this.data.title;
url = this.data.url;
ups = this.data.ups;
downs = this.data.downs;
total += (ups - downs);
numberOfEntries += 1;
$("#redditbox").append("<p>" + ups + ":" + downs + " " + title + "<p>");
$("#redditbox :last-child").css('font-size', ups%20); //This is the line in question
});
$("#titlebox h1").append(total/numberOfEntries);
});
}
populatePage()
$(".button").click(function() {
populatePage();
});
});
Unfortunately things are not quite working out as planned. The styling at the line in question is applying to every child of the div, not just the one that happens to be appended at the time, so they all end up the same size, not sized dependent on their numbers.
how can I apply a style to the p tags as they are appended ot the div?
Edit: Thanks Fortes and Veggerby both worked, but i went with Fortes in the end because I did.
You can use JQuery's appendTo instead of append. For your example:
$("<p>" + ups + ":" + downs + " " + title + "<p>")
.css('font-size', ups%20)
.appendTo('#redditbox');
Here are the docs for appendTo: http://docs.jquery.com/Manipulation/appendTo
Replace:
$("#redditbox").append("<p>" + ups + ":" + downs + " " + title + "<p>");
with
var p = $("<p>" + ups + ":" + downs + " " + title + "<p>");
$("p", p).css('font-size', ups%20)
$("#redditbox").append(p);
Can probably be condensed even further.
Edit:
Condensed like:
$("#redditbox").append(
$("<p></p>").css('font-size', ups%20).append(ups + ":" + downs + " " + title + "")
);
Certain browsers/versions do not support the :last-child CSS selector. In that case they often ignore it and return all elements matching the remainder of the selector. This is possibly what you are seeing.
As usual IE is one such browser.
veggerby's approach should help you get around the need to use :last-child.

Categories

Resources