Javascript Loop Iteration Issue - javascript

I want to run a for loop that will produce a new div (with class 'container') containing a single link. E.g. the first div will show 'link6.php', the second div will show 'link5.php' etc. However, currently it seems that the loop is running out the full loop in each div (I have attached a picture showing this).
for (var i = 6; i > 0; i--) {
$('#everything').append('<div class="container"></div>');
var link = "link" + i + ".php" + "<br />";
$('.container').append(link);
}
Thank you very much in advance. I am new at this and your help is much appreciated ;)

The problem is that after you append the div, you select all .container elements and append the text to each. There seems to be no reason why you couldn't do the following.
for (var i = 6; i > 0; i--) {
$('#everything').append('<div class="container">link'+i+'.php<br /></div>');
}

This is my recommendation for your code. I recommend you to cache things first, and understand how jQuery's DOM selection works.
var everythingCached = $('#everything');
var container = $('<div class="container"></div>');
for (var i = 6; i >0; i--) {
var cached = everythingCached.append(container);
var link = "link" + i + ".php" + "<br />";
cached.append(link);
}
https://jsfiddle.net/47g4f14p/

When you do $(".container").append(), it appends to every DIV with class="container", not only the one you just appended in this loop.\
The simple way to fix this is to include link in what you append to #everything.
for (var i = 6; i > 0; i--) {
var link = "link" + i + ".php" + "<br />";
$('#everything').append('<div class="container">' + link + '</div>');
}
Or you could create the container as an object:
$('#everything').append($('<div>', {
"class": "container",
html: "link" + i + ".php<br/>"
});
or you could assign the container to a variable and append to it:
var container = $('<div class="container">').appendTo("#everything");
var link = "link" + i + ".php" + "<br />";
container.append(link);

The problem is because everytime you do $('.container').append(link);, the $('.container') gathers all existing divs including the ones added in the previous iterations and appends your link to each.
Instead of re-gathering them, reuse the existing reference to the container. You can chain append and appendTo.
for (var i = 6; i > 0; i--) {
$('<div class="container"/>') // create container
.append("link" + i + ".php") // append container with link
.appendTo('#everything'); // append container to everything
}
#everything {
padding: 10px;
border: 1px solid blue;
}
.container {
padding: 10px;
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="everything"></div>

You're giving each div the class of 'container' and then running the append() on all .containers.
You need to give the divs a unique ID, or refer to it directly by the object.
As an example:
for (var i = 6; i > 0; i--) {
$('#everything').append('<div class="container'+i+'"></div>');
var link = "link" + i + ".php" + "<br />";
$('.container'+i).append(link);
}

Related

how to highlight a table cell onClick with unique colors in each cell

In the fiddle below, you can click on any of the cells and they will change colors to those in td.highlighted in the CSS. I want the highlighted color to be assigned inline instead and unique to each element.
https://jsfiddle.net/rvxnmz8r/7
this is the line that generates the style for each table element, and I think the main problem is that I am dumb with CSS. Thanks for any help.
var hstyle = 'style="td.highlighted {background-color: ' + '#'+Math.random().toString(16).substr(-6) + '; color: black;}"';
update: the cells need to remain toggle-able between the default and custom highlighted colors.
When using inline style combined with external CSS, the external need !important to override the inline style.
As a side note, using !important impact the usability of styling in a more difficult way to reuse, though, in your case, create 60 classes to toggle, I found more bad, hence the use of !important
Change your script to
var hstyle = 'style="background-color: ' + '#' + Math.random().toString(16).substr(-6) + '; color: black;"';`
And your CSS to
td.highlighted {
background-color: blue !important;
color: white !important;
}
Stack snippet
var elements = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var transtable = [elements, elements, elements, elements, elements, elements];
var output = [];
output.push('<table id="taxatable">');
for (var row = 0; row < transtable[0].length; row++) {
output.push('<tr>');
for (var col = 0; col < transtable.length; col++) {
var hclass = 'class="highlighted"';
var hstyle = 'style="background-color: ' + '#' + Math.random().toString(16).substr(-6) + '; color: black;"';
output.push(
'<td ' + hclass + ' ' + hstyle + '>' + escape(transtable[col][row]) + '</td>'
);
}
output.push('</tr>');
}
output.push('</table>');
document.getElementById('output').innerHTML = output.join('');
var tbl = document.getElementById("taxatable");
if (tbl != null) {
for (var trow = 0; trow < tbl.rows.length; trow++) {
for (var tcol = 0; tcol < tbl.rows[trow].cells.length; tcol++) {
tbl.rows[trow].cells[tcol].onclick = function() {
this.classList.toggle("highlighted");
};
//console.log(tbl.rows[trow].cells[tcol]);
}
}
}
td {
background-color: black;
color: white;
}
td.highlighted {
background-color: blue !important;
color: white !important;
}
<div id="output">
</div>
Edit
I see what you’re trying to do, but your solution is mixing two things together: inline styles and CSS rules. You can only use style="" on an element to set styling directly on that element, which overrides the rules from your stylesheet. If you want to toggle the highlight class on and off you could do something like this (using jQuery):
$("td").click(function() {
$(this).toggleClass('highlighted');
});
Also, it needs the !important modifier in the highlighted class, as #LGSon explains above.
In combination with my answer below (removing td.highlighted in the inline style), this should probably result in what you are looking for.
Old answer
If you use inline styles, you are styling directly on the HTML element and you won’t need to define a CSS selector. Instead of
var hstyle = 'style="td.highlighted {background-color...
you can simply write:
var hstyle = 'background-color...'
So, your code becomes:
var hstyle = 'style="background-color: ' + '#'+Math.random().toString(16).substr(-6) + '; color: black;"';
You were close. Remove the td.highlighted like so
var hstyle = 'style="background-color: ' + '#'+Math.random().toString(16).substr(-6) + '; color: black;"';

Get input value from input in array

So, this is kinda difficult to explain, and also to search for.
My situation:
i have a webpage which allows users to fill up to 48 time fields, all these time fields are dynamically generated, each with an ID of their own, all in a div.
Now, the user also has the option to delete a field, in any place. In this case i want to re-order them all.
Example: user has timebox 1 to 8, removes 5.
6 becomes 5, 7 becomes 6, 8 becomes 7.
This should also count for the ID's.
Now, when a user deletes a box, i pick up all the divs in a specific div (DailyControls) and put them in an array. All of these divs have a class named timepicker.
Now i need to get the value from the input boxes which are now also stored in the array.
This is for creating the textboxes (with the div, some text infront and the remove button)
var newTextBoxDiv = $(document.createElement('div')).attr("ID", 'time' + boxID);
newTextBoxDiv.after().html('<label>Herrinering #' + boxID + ' : </label>' +
'<input type="text" name="timebox' + boxID +
'" id="timebox' + boxID + '" value="" class="timepicker" >' + '<img src="<%= Page.ResolveUrl("~") %>images/ico_delete.png" id="Delete'+ boxID +'" onclick="DeleteTime()"/>');
newTextBoxDiv.attr("class", "timerdiv");
To remove them i am currently using the following:
function DeleteTime() {
var id = event.target.id;
var IdNO = id.replace("Delete", "");
$("#time" + IdNO).remove();
var elemdivs = [];
for (var i = 0; i < $(".timerdiv").length; i++) {
elemdivs.push($(".timerdiv")[i].innerHTML);
}
$('.timerdiv').remove();
for (var i = 0; i < elemdivs.length; i++) {
alert(elemdivs[i]);
}
};
in the alert i can see the input element, and also the div ect.
But i dont know how to get the value from there
Based on the information you provided this would probably work:
function DeleteTime() {
var id = event.target.id;
var IdNO = id.replace("Delete", "");
$("#time" + IdNO).remove();
var elemdivs = [];
for (var i = 0; i < $(".timerdiv").length; i++) {
elemdivs.push($(".timerdiv")[i]); // don't push innerHTML
}
$('.timerdiv').remove();
for (var i = 0; i < elemdivs.length; i++) {
alert($(elemdivs[i]).find('input').val());
}
};
Instead of inserting the innerHTML from your timerdiv into the you put in the timerdiv itself. Then when accessing it you .find() the input field inside of the timerdiv ($(elemdivs[i])) and then get the .val() from that.

Adding a <span> to each letter in responsive wordpress theme

I want to create separate backgrounds for each letter in the site-description span within the header on the Wordpress responsive theme.
I have added a function in functions.php
<?php
/**
* Setup Responsive Child Theme Functions
*/
function site_description_spans() {
echo 'Text within header'; // Replace this line with code from `https://stackoverflow.com/questions/17517816/color-every-character-differently
}
add_action( 'responsive_in_header', 'site_description_spans' );
?>
This successfully targets within the header within the responsive theme
But then I tried to add the following code within this function from another Stack Exchange post by replacing the
echo 'text within header' //above
The link to the javascript function on stack exchange is here
Color every character differently
and the relevant code is
$('.site-description').find('span').each(function(){
var $el = $(this),
text = $el.text(),
len = text.length,
newCont = '';
for(var i=0; i<len; i++){
var bgColor= '#'+ (Math.random() * 0xffffff).toString(16).substr(-6);
newCont += '<span style="background:'+bgColor+'">'+ text.charAt(i) +'</span>';
}
$el.html(newCont);
});
And it doesn't seem to work. Would be grateful for any suggestions.
Now i'm not too sure on the outputted HTML but i'm going to take a wild guess, that this is how the HTML is being output:
<span class="site-description">
Text within header
</span>
What you need if the code is to work as expected
<div class="site-description">
<span>
Text within header
</span>
</div>
Option 1 - Change HTML
Change your HTML code so that a span is contained within a div and the function to add the text is within the span
Something like this
<div class="site-description">
<span>
<!-- RUN FUNCTION HERE -->
</span>
</div>
Option 2 - Change jQuery
Change your jQuery function to something like this:
$('.site-description').each(function() {
var $el = $(this),
text = $el.text(),
len = text.length,
newCont = '';
for (var i = 0; i < len; i++) {
var bgColor = '#' + (Math.random() * 0xffffff).toString(16).substr(-6);
newCont += '<span style="background:' + bgColor + '">' + text.charAt(i) + '</span>';
}
$el.html(newCont);
});
Or generally just fix the first part of the query so that it finds the correct class or element.
Ok,
I have tried option 2 and just inserted it in the original function but I am not really sure what I am doing here. I understand what you suggested in option 2 and it looks like that would work, I am just not sure how to add it as a function in functions.php
This is what I have
function site_description_spans() {
$('.site-description').each(function() {
var $el = $(this),
text = $el.text(),
len = text.length,
newCont = '';
for (var i = 0; i < len; i++) {
var bgColor = '#' + (Math.random() * 0xffffff).toString(16).substr(-6);
newCont += '<span style="background:' + bgColor + '">' + text.charAt(i) + '</span>';
}
$el.html(newCont);
});
}
add_action( 'responsive_in_header', 'site_description_spans' );
?>
Trouble is that I get the following error with it
Parse error: syntax error, unexpected '(', expecting T_VARIABLE or '$' in /***/*****/public_html/*****/dev/wp-content/themes/responsive_child/functions.php on line 11

Generate multiple div in jquery loop

I need to ask for help.
Having this code:
$(".apprezzamenti").click(function()
{
var id = $(this).attr('id');
$.get("http://localhost/laravel/public/index.php/apprezzamenti_modal/"+id,
function(data)
{
data_parsed = JSON.parse(data);
// BELOW is the loop that I would like to generate multiple div using .append()
for(var i=0; i<data_parsed.length; i++)
{
var html = '<img src="images/provvisorie/immagine-profilo.png" width="30px" and height="30x" />';
html += ' ';
html += "<a href='http://localhost/laravel/public/index.php/utente/" + data_parsed[i].id_user + "' style='font-weight: bold;'>" + data_parsed[i].username + "</a>";
$(".modal-body-apprezzamenti>p").append(html).append('.modal-body-apprezzamenti>p').append($('<br/>'));
}
$(".chiudi-popup").click(function()
{
$(".modal-body-apprezzamenti>p").html('');
});
$('#main').click(function()
{
$(".modal-body-apprezzamenti>p").html('');
});
});
});
I'd like to create a div for each looping.
How could I do? Thanks for your help.
With jQuery it's very easy, look at this JSFiddle
http://jsfiddle.net/Ldh9beLn/
I use the function jQuery appendTo() to insert each div inside another div with id = "inserts" if you don't understand a section of this code or how to adapt to yours leave me a comment.
var things = ["apple", "house", "cloud"];
for (var i = 0; i < things.length; i++) {
$("<div>"+things[i]+"</div>").appendTo("#inserts");
}

How to make list in jQuery mobile nested list?

Can you please tell me how to make list in jQuery mobile? I am trying to make this type list as given in fiddle on pop up screen dynamically .
Here is the fiddle
In this fiddle I make two rows.In first row there is only p tag. But in second row there is nested collapsible rows. I need to make same thing in pop up screen. I am able to make first row. But In my second row contend is null why? Can you suggest where I am wrong?
fiddle
$(function () {
$('#test').click(function(){
alert('d');
createCommandPopUpTabs();
$("#tabbedPopup").popup("open");
});
});
var tabsHeader = [ "InputParameter", "basic"];
var tabsHeader_basic = [ "XYZ", "Third Level",
];
function createCommandPopUpTabs(){
var header = "<h3 >dd</h3>";
var commmand = 'dd';
var button = '<button onclick="return submitCommand("'+
'")" style="" class="donebtn common-button1">Save</button>';
$("#commandInfo").append(button);
$("#commandInfoheader").html(header);
for ( var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>InputParameter</h3></div>";
var content ;
if(tabsHeader[i]=="InputParameter"){
content = "<p>yes</p>";
}else if(tabsHeader[i]=="basic"){
for ( var i = 0; i < tabsHeader_basic.length; i++) {
headerId = tabsHeader_basic[i] + "_tab" + commmand;
header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>basic</h3></div>";
content += getcontend(tabsHeader_basic[i]);
}
}
$("#tabbedSet").append(header);
$("#tabbedSet").find("#" + headerId).append(content);
$("#tabbedSet").collapsibleset("refresh");
}
}
function getcontend(name){
if(name=="Third Level"){
return"<p>Third Level></p>";
} if(name=="XYZ"){
return"<p> second Level></p>";
}
}
There are errors in your code and logic. I will only go over a couple of them to hopefully get you on the right path:
In tabsHeader_basic array the Third Level has a space in it which you later use as an ID which makes it an invalid ID because you cannot have spaces in an ID.
From the HTML 5 Draft:
The value must not contain any space characters.
Also, the "basic" collapsible div needs to exist before you start adding the nested collapsible div.
So this line needs to come out of the for loop
header = "<div data-role='collapsible' data-collapsed='false' id='"+ headerId + "'><h3>basic</h3></div>";
Go through the JSFiddle and compare your code agaisnt my changes.
Hopefully that helps! Let me know if you have any other questions.
I have updated createCommandPopUpTabs() function.
Also removed space in Third Level on var tabsHeader_basic = ["XYZ", "ThirdLevel"];
Check the Updated Fiddle
function createCommandPopUpTabs() {
var header = "<h3 >dd</h3>";
var commmand = 'dd';
var button = '<button onclick="return submitCommand("' +
'")" style="" class="donebtn common-button1">Save</button>';
$("#commandInfo").html(button);
$("#commandInfoheader").html(header);
$("#tabbedSet").html('');
for (var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='true' id='" + headerId + "'><h3>" + tabsHeader[i] + "</h3></div>";
$("#tabbedSet").append(header);
var content;
if (tabsHeader[i] == "InputParameter") {
content = "<p>yes</p>";
$("#tabbedSet").find("#" + headerId).append(content);
} else if (tabsHeader[i] == "basic") {
for (var j = 0; j < tabsHeader_basic.length; j++) {
var headerId1 = tabsHeader_basic[j] + "_tab" + commmand;
var header1 = "<div data-role='collapsible' data-collapsed='true' id='" + headerId1 + "'><h3>" + tabsHeader_basic[j] + "</h3></div>";
var content1 = getcontend(tabsHeader_basic[j]);
$("#tabbedSet").find("#" + headerId).append(header1);
$("#tabbedSet").find("#" + headerId1).append(content1);
}
}
$("#tabbedSet").collapsibleset("refresh");
}
}

Categories

Resources