I have a div with an ID "orangeButton" and each time you click on it it creates a new div. This works fine but... I want each newly created div to have an incremental number added to it's ID.
I am not sure how to do this.
Here is a fiddle of the code I have thus far with comments.
http://jsfiddle.net/taoist/yPrab/1/
Thank you
Javascript Code
var applicationArea = document.getElementById("applicationArea");
var orangeButton = document.getElementById("orangeButton");
orangeButton.onclick = function() {
var newDivThingy = document.createElement("div");
newDivThingy.id = 'newDivThingy'; // I want each newly created div to have a numeric value concatenated to it's ID. IE newDivThingy1 newDivThingy2 newDivThingy3
applicationArea.appendChild(newDivThingy);
};
Am I missing something, why not use a counter?
var counter = 0;
button.onclick = function(){
var newDivThingy = document.createElement("div");
newDivThingy.id = 'newDivThingy' + (++counter);
// continue your stuff here
}
Libraries like underscorejs provide a uniqueid function for this. Otherwise its easy to implement one.
myNamespace.uniqueId = (function () {
var counter = 0; // in closure
return function (prefix) {
counter++;
return (prefix || '') + '-' + counter;
};
}());
Usage.
newDiv.id = myNamespace.uniqueId('newDiv');
Simply use a integer and increment it as each element is added.
var applicationArea = document.getElementById("applicationArea"),
orangeButton = document.getElementById("orangeButton"),
counter = 1;
orangeButton.onclick = function() {
var newDivThingy = document.createElement("div");
newDivThingy.id = "newDivThingy" + counter++;
applicationArea.appendChild(newDivThingy);
}
I have no doubt you have solution and may have forgotten this post.
BUT, I wold like to show a solution that is a compact format.
Note the counter is set to (counter++) so it will start at 1.
var orangeButton = document.getElementById("orangeButton");
var counter = 0;
orangeButton.onclick = function() {
document.getElementById('applicationArea')
.appendChild(document.createElement('div'))
.setAttribute("id", 'newDivThingy' + counter++);
// I want each newly created div to have a
// numeric value concatenated to it's ID.
// IE newDivThingy1 newDivThingy2 newDivThingy3
};
Related
So let's say that I have a variable, slide1.
var slide1 = $('#slide1');
How can I concatenate a string, such as 'slide,' with an integer to make it equal to and behave just like that above variable, slide1?
showThis('slide' + 1);
Here is my fiddle, so you can see a shortened version of my issue/confusion in action. As you'll see, the result of the concatenation is not hiding as I would expect.
Am I attempting to do something completely taboo?
Thanks in advance!
var slide1 = $('#slide1');
var button = $('#button');
button.click(function() {
showThis('slide' + 1);
});
function showThis(thisSlide) {
alert(thisSlide);
$("#" + thisSlide).hide();
}
Your showThis() function requires a Jquery object and what you are providing is a string. So your code should actually be this
showThis($('#slide' + 1));
you need to index into the global window object if you really want to do it this way.
var slide1 = $('#slide1');
var button = $('#button');
button.click(function() {
showThis(window['slide' + 1]);
});
function showThis(thisSlide) {
alert(thisSlide);
$(thisSlide).hide();
}
however i would go with an array like the other posters have responded with
You can access properties of an object with strings, but not really variables.
Like, you have an object
var slide = {
slide1: $('#slide1'),
var button = $('#button'),
}
You could access slide1 with a string like this
showThis(slide['slide'+1]);
The way you are trying isn't a valid way to access variables.
Any reason you can't use an array? eg:
var slides = [];
slides[0] = $('#slide0');
slides[1] = $('#slide1');
//etc
showThis(slides[1]);
or even:
var slides = [];
for(var i = 0; i< 10; i++){
slides[i] = $('#slide' + i);
}
showThis(slides[1]);
I am trying to create a dynamic list so when the user performs a search it will repopulate the list. The problem is that I can't seem to make an immutable constant to store the original div content. Every time the function get's called this variable gets reinitialized.
Is there a way to achieve this without using cookies ? Any help is sincerely appreciated. The code is not complete because I couldn't get passed this step but if you think I am totally heading toward the wrong direction please let me know.
const originalList = document.getElementById('patientList').getElementsByTagName('li');
frozen = Object.freeze(originalList);
<script>
const originalList = document.getElementById('patientList').getElementsByTagName('li');
frozen = Object.freeze(originalList);
var newList = '';
var found = false;
function filterPatients(){
var searchQuery = document.getElementById('search');
var query = searchQuery.value;
var listContainer = document.getElementById('patientList');
var patientList = listContainer.getElementsByTagName('li');
for (var i = 0; i < originalList.length; i++){
var link = patientList[i].getElementsByTagName('a');
var link = link[0].text;
/** remove whitespaces for easy comparison **/
link = link.toLowerCase();
query = query.toLowerCase();
link = link.replace(/\s/g, "");
query = query.replace(/\s/g, "");
/** check every character in query **/
if (link.length > query.length && link.substring(0,query.length) == query){
found = true;
newList += '<li>' + patientList[i].innerHTML + '</li>';
}
}
if (found == true){
listContainer.innerHTML = newList;
newList = '';
}
else{
listContainer.innerHTML = "<li>No patient by that name</li>";
}
console.log(frozen);
}
</script>
const originalList = document.getElementById('patientList').getElementsByTagName('li').cloneNode(true);
Make originalList a copy of the element. Currently, you are setting originalList and patientList to be the same list of elements, so changing one will also change the other. Use element.cloneNode(true) to make a deep copy of a DOM element
I have a Jquery function that helps with validation over 1 object. I need to expand it so that the function will run over 3 different objects. I am trying to define a function that takes a parameter(whichquote) to insert the appropriate object in the function. Here is my code. What I am doing wrong? I assume I do not have the selector correct as the code works if I put it in.
Original Function that works:
var depends = function() {
var selectorD = $("input[name^='lead[quote_diamonds_attributes]'], select[name^='lead[quote_diamonds_attributes]']");
var vals = '';
selectorD.not(':eq(0)').each(function () {
vals += $(this).val();
});
return vals.length > 0;
};
Function I am trying to create that allows me to use it on other objects. This currently does not work.
var depends = function(whichquote) {
var selectorD = $("input[name^='lead[+ whichquote +]'], select[name^='lead[+ whichquote +]']");**
var vals = '';
selectorD.not(':eq(0)').each(function () {
vals += $(this).val();
});
return vals.length > 0;
};
I think the problem is with my concating in the var selectorD but cannot seem to get the syntax correct.
Your selector isn't actually inputting whichquote because the string concatenation is incorrect.
Try
var selectorD = $("input[name^='lead[" + whichquote + "]'], select[name^='lead[" + whichquote +"]']");
So I am working on a project of mine and I'd like some help.
I'd like javascript to be able to count in seconds, each second it'd add a preset amount of points.
var total_points = 0
var points_per_click = 1
var points_per_second = 0
function points_per_second() {
docuement.getElementById("current_points").innerHTML("Current Points: " + total_points);
//insert here?
}
I would also like the points_per_second to be able to add into the total_points var. Thanks!
docuement is spelt "document", .innerHTML is not a function call (set it like a variable) & variables and functions share the same namespace, i.e. don't set a variable points_per_second and then declare a function of the same name.
Once you have your syntax errors sorted, you were probably looking for setInterval.
var total_points = 0;
var points_per_click = 1;
var points_per_second = 2;
function update_display(){
var el = document.getElementById("current_points");
el.innerHTML = "Current Points: " + total_points;
//insert here? ... No
}
var ticker = setInterval(function(){
total_points += points_per_second;
// ... or whatever your intended logic
update_display();
}, 1000);
jsFiddle
Hi all i am trying to change the html of an object from an array of htmls. But i am having problem iterating properly. I managed to make it work once
EDIT
After a few complains about the clarity of my question I will rephrase it. I have a div panel called .trpanel and a button called #trigger2 (it is a next button). Then I have a series of divs with texts that contain translations. I want when I press the button (called next) to cycle through the translations one by one on the trpanel.
var ltranslation = [];
ltranslation[0] = $("#translation-en-1").html();
ltranslation[1] = $("#translation-ur-en").html();
ltranslation[2] = $("#translation-fr-en").html();
ltranslation[3] = $("#translation-it-en").html();
ltranslation[4] = $("#translation-sp-en").html();
ltranslation[5] = $("#translation-po-en").html();
ltranslation[6] = $("#translation-fr-en").html();
ltranslation[7] = $("#translation-de-en").html();
var l= ltranslation;
$("#trigger2").off('click').on('click',function(){
for (var i = 0; i <= ltranslation.length; i++){
if (i==7){i=0;}
$(".trpanel").html.ltranslation[i]; or ???//replace().ltranslation[]+i??? the code throws errors
}
});
I am quite new to Javascript and i am getting a bit confused with the types of objects and arrays and loops. I managed once to add the htmls but without replacing them ... so they all came one after the other. The i tried to change the code and it hasn't worked since. Any help will be greatly appreciated.
A lot of guessing, but seems like you are trying to do this :
var trans = $('[id^="translation-"]'),
idx = 0;
$("#trigger2").on('click',function(){
$(".trpanel").html( trans.eq(idx).html() );
idx = idx > 6 ? 0 : idx+1;
});
FIDDLE
I think you are trying to do this:
if (i == 7) {
i = 0; // I don't really know why you are doing this, but it will reset the loop
}
$(".trpanel").html(ltranslation[i]); //I'm passing ltranslation[i] to the html method. Instead of .html.ltranslation[i].
}
Also, without seeing any html, I'm not sure but I think you may want to iterate over .trpanel ?
Something like:
$(".trpanel").eq(i).html(ltranslation[i]);
Another thing (so you can make your code clearer I think). You can abstract the array population in a function, like this:
var ltranslation = [];
var languages = ["en-1", "ur-en", "fr-en", "it-en", "sp-en", "po-en", "fr-en", "de-en"];
$.each(languages, function(index) {
ltranslation[index] = $("#translation-" + this).html();
});
// Then you can use ltranslation
If you want to flip through several translations I would implement it that way:
var translations=["hej","hello", "hallo","hoy"];
var showTranslation=function(){
var current=0;
var len=translations.length;
return function(){
var direction=1;
if (current>=len) current=0;
$("#text").text(translations[current]);
current+=direction;
}
}();
$("#butt").on("click", showTranslation);
Fiddle: http://jsfiddle.net/Xr9fz/
Further: You should give your translations a class, so you could easily grab all of them with a single line:
$(".translation).each(function(index,value){ ltranslation.push(value); })
From the question : I managed once to add the htmls but without replacing them -
I think you want to add all of these items into $(".trpanel"). First, dont take the HTML of each element, clone the element itself :
//method ripped from Nico's answer.
var ltranslation = [];
var languages = ["en-1", "ur-en", "fr-en", "it-en", "sp-en", "po-en", "fr-en", "de-en"];
$.each(languages, function(index) {
ltranslation[index] = $("#translation-" + this).clone();
});
Then you could append everything into the container, so add the htmls but without replacing them. append takes in an array without replacing the previous html.
$("#trigger2").off('click').on('click',function() {
$(".trpanel").append(ltranslation);
});
I don't know what exactly you're tring to do, but I've put comments in your code to help you better understand what your code is doing. The net effect of your code is this (which I doubt you want) :
$("#trigger2").off('click').on('click',function(){
$(".trpanel").html(ltranslation[7]);
});
This is your code with some comments and minor changes
var ltranslation = [];
ltranslation[0] = $("#translation-en-1").html();
ltranslation[1] = $("#translation-ur-en").html();
ltranslation[2] = $("#translation-fr-en").html();
ltranslation[3] = $("#translation-it-en").html();
ltranslation[4] = $("#translation-sp-en").html();
ltranslation[5] = $("#translation-po-en").html();
ltranslation[6] = $("#translation-fr-en").html();
ltranslation[7] = $("#translation-de-en").html();
var l= ltranslation;
$("#trigger2").off('click').on('click',function(){
for (var i = 0; i < ltranslation.length; i++){
//if (i==7){i=0;} <-- This will cause an infinite loop won't it? are you trying to reset i? i will reset next time loop is called,
$(".trpanel").html(ltranslation[i]); //<-- this will overwrite elements with class .trpanel ltranslation.length times...
///you'll see only the value of translation[7] in the end
}
});
EDIT
To do what you want to do based on your comments, try this:
var ltranslation = [];
ltranslation[0] = $("#translation-en-1").html();
ltranslation[1] = $("#translation-ur-en").html();
ltranslation[2] = $("#translation-fr-en").html();
ltranslation[3] = $("#translation-it-en").html();
ltranslation[4] = $("#translation-sp-en").html();
ltranslation[5] = $("#translation-po-en").html();
ltranslation[6] = $("#translation-fr-en").html();
ltranslation[7] = $("#translation-de-en").html();
var counter = 0;//a global counter variable
$("#trigger2").click(function(){ //eeverytime button is clicked do this
$(".trpanel").html(ltranslation[counter]); //set the html to an element of array
counter++; //increment counter
if(counter==ltranslation.length) //reset the counter if its bigger than array len
counter=0;
});