I need to create a set amount of buttons using jquery. I've tried a for loop and a while loop but this isn't working.
I'm storing the amount of pages I need in a variable 'pages', which when using console.log(pages) correctly shows how many buttons I require yet I still can't get the loop to work.
while (i <= pages) {
pageButtons.append('<input type="button" id="button'+i+'" value="Random'+i+'"/>');
i = i + 1;
}
I currently have the above code..
What is pageButtons assigned to? If you contain all of the buttons in a div, this will work
var pages = 5;
var pageButtons = $('#pageButtons');
for (var i = 0; i < pages; i++) {
pageButtons.append('<input type="button" id="button' + i + '" value="Random' + i + '"/>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pageButtons">
</div>
You would want to do something like this:
var pages = 5;
for (var i = 0; i <= pages; i++) {
$('#buttons').append('<input type="button" id="button' + i + '"value="Random' + i + '"/>');
}
http:////jsfiddle.net/clccmh/x545y8re/
Related
I have a block of code under a div element "questionform" and want to allow the code to repeat, depending on the number of times the user would like it to, to eventually allow the user to make a quiz.
I have tried to create a bit of javascript in order to repeat just the question number for now, but it won't work.
<div id="myHTMLWrapper">
</div>
<script>
var wrapper = document.getElementById("myHTMLWrapper");
var number = prompt("Enter the number of questions");
for (var i = 0; i = number - 1; i++) {
myHTML += '<span class="test">Question' + (i + 1) + '</span><br/><br/>';
}
wrapper.innerHTML = myHTML
</script>
any help will be appreciated, and please dont just point out flaws and not tell me how to improve them.
You have two issues in your code. firstly, you have to declare the variable myHTML outside the loop with empty string. Secondly, in the loop i = number - 1 will prevent the iteration of the loop, try i < number
<div id="myHTMLWrapper">
</div>
<script>
var wrapper = document.getElementById("myHTMLWrapper");
var number = prompt("Enter the number of questions");
var myHTML = '';
for (var i = 0; i < number; i++) {
myHTML += '<span class="test">Question ' + (i + 1) + '</span><br/><br/>';
}
wrapper.innerHTML = myHTML;
</script>
Though, here starting the loop iteration value from 1 with i <= number is more meaningful as this will allow you to use the value directly (without the increment) in the htmlString:
<div id="myHTMLWrapper">
</div>
<script>
var wrapper = document.getElementById("myHTMLWrapper");
var number = prompt("Enter the number of questions");
var myHTML = '';
for (var i = 1; i <= number; i++) {
myHTML += '<span class="test">Question ' + i + '</span><br/><br/>';
}
wrapper.innerHTML = myHTML
</script>
Let's say I have an array of links like this:
var playlist = [
"",
"https://www.youtube.com",
"https://www.google.com",
"https://www.facebook.com",
"https://www.instagram.com"
];
And a bunch of boxes generated in the following way:
for(var i = 1; i < 5; i++) {
$(".container").append("<div class='luke luke-" + i + "'>" + "<h3 class='nummer'>Luke " + i + "</h3> " + "</div>");
}
I then want to iterate through this array to open a specific link when a box is clicked.
for(var i = 1; i < 5; i++) {
$(".luke-" + i).click(function(){
window.open(playlist[i], "_blank");
})
}
That doesn't seem to work at all, however the example below does exactly what I want.
$(".luke-1").click(function(){
window.open(playlist[1], "_blank");
})
$(".luke-2").click(function(){
window.open(playlist[2], "_blank");
})
$(".luke-3").click(function(){
window.open(playlist[3], "_blank");
})
$(".luke-4").click(function(){
window.open(playlist[4], "_blank");
})
$(".luke-5").click(function(){
window.open(playlist[5], "_blank");
})
So this works, but it's a pain in the ass to setup as I want to have 25 boxes in total and this solution offers little to no flexibility if I want to increase or decrease that amount at a later time. What am I doing wrong with the for-loop that's causing issues here?
If I use
console.log(playlist[i]);
inside of the for-loop, it simply returns "undefined" regardless of what box I click in case that helps.
You can do this much easier and simpler using a data attribute.
HTML
<div class="container"></div>
Javascript/jQuery
var playlist = [
"",
"https://www.youtube.com",
"https://www.google.com",
"https://www.facebook.com",
"https://www.instagram.com"
];
for(var i = 1; i < 5; i++) {
$(".container").append("<div class='luke' data-url='" + playlist[i] + "'>" + "<h3 class='nummer'>Luke " + i + "</h3> " + "</div>");
}
$('.luke').click(function() {
window.open($(this).data('url'));
});
Demo Here
You are not doing right.
EXAMPLE FIDDLE
var playlist = [
"https://www.youtube.com",
"https://www.google.com",
"https://www.facebook.com",
"https://www.instagram.com"
];
var container = $("#container");
for(var i = 1; i < 5; i++) {
container.append('<div class="luke" db-id="'+ i + '"><h3 class="nummer">Luke ' + i + '</h3></div>');
}
$(".luke").click(function(i){
window.open(playlist[$(this).attr('db-id')], "_blank");
});
for(var i = 1; i < 5; i++) {
$(".luke-" + i).click(function(i){
window.open(playlist[i], "_blank");
})
}
The click event will launch your function only inside the scope of the loop. This means that once the loop have finished, ( and counting from 0 to 5 is insanely fast for your computer ) there's no more function attached to your click event. In other terms, as long as i < 5, your click function will work as you expect, but after that, the click event will no longer call the function you created.
One solution could to be attach a function to the onclick attribute in the HTML like this :
for(var i = 1; i < 5; i++) {
$('<div/>', {
'class': 'luke luke-' + i,
'click': yourFunction(i)
}).appendTo(${'.container'});
$('<h3/>', {
'class':'nummer',
'html': 'Luke' + i
}).appendTo(${'.luke-'+i})
}
and then write a function like this :
function yourFunction(index){
window.open(playlist[index], "_blank");
}
Simple way by using Hyperlink
hyperlinks
Demo Here
I have the following code:
for (i = 0; i < 13; i++){
$('.players').append('<div class="rule_dropdown"><select name="rule' + i + '">');
for(j = 0; j < rules.length; j++){
$('.players').append('<option>' + rules[j] + '</option>');
}
$('.players').append('</select></div>');
}
I want to have 13 dropdown lists with the same content. I expect this to happen:
First for loop add an opening div and select
For each rule in rules array, append an option
Add closing select and closing div
Go back to #1
But this is what actually happens:
First loop add opening AND closing div and select.
Second loop add option with the right content
Does anyone know why?
I think this is what you want to do..
var rules=[1,2,3,4,5,6];
for (i = 0; i < 13; i++){
$('.players').append('<div class="rule_dropdown"><select id="rule'+ i +'" name="rule' + i + '">');
for(j = 0; j < rules.length; j++){
$('#rule'+i).append('<option>' + rules[j] + '</option>');
}
$('.players').append('</select></div>');
}
I think append adds a full element to the DOM rather than just adding the text into the HTML as it were. Try building up your elements individually and adding them a bit like this:
for (i = 0; i < 13; i++){
var $select = $('<select name="rule' + i + '"></select>');
for(j = 0; j < rules.length; j++) {
$select.append('<option>' + rules[j] + '</option>');
}
var $div = '<div class="rule_dropdown"></div>';
$div.append($select);
$('.players').append($div);
}
From the documentation:
The .append() method inserts the specified content as the last child of each element in the jQuery collection.
The options you want to add should be the child elements of the select, not the div.
Am trying to write using document.write() an image at the time from my array. However it does not display any...
// *** Temporal variables
var i = 0;
var j = 0;
var x = 0;
// Create basic linear array
var ImgArray = []
// Do the 2D array for each or the linear array slots
for (i=0; i < 4 ; i++) {
ImgArray[i] = []
}
// Load the images
x = 0;
for(i=0; i < 4 ; i++) {
for(j=0; j < 4 ; j++) {
ImgArray[i][j] = new Image();
ImgArray[i][j] = "Images/" + x + ".jpg";
document.write("<img id= " + x + " img src=ImgArray[i][j] width='120' height='120'/>");
x = x + 1;
}
document.write("<br>");
}
What am I doing wrong?
Looks like your JavaScript isn't quite right...
document.write('<img id="' + x + '" src="' + ImgArray[i][j] + '" width="120" height="120"/>');
It looks like you're trying to do image preloading by using new Image(), but then you immediately write out an image element with the same src using document.write(), so the image will not have preloaded and you get no benefit. I also suspect you're missing a .src on one line in the inner loop:
ImgArray[i][j].src = "Images/" + x + ".jpg";
This looping to create image elements would be best done server-side when generating the HTML, but assuming that's not an option, you could lose the ImgArray variable completely:
x = 0;
for(i=0; i < 4; i++) {
for(j=0; j < 4; j++) {
document.write("<img id='" + x + "' src='Images/" + x + ".jpg' width='120' height='120'>");
x = x + 1;
}
document.write("<br>");
}
document.write writes any input the the location of script element. Try this instead:
in body
<div id="imageContainer"></div>
in your script, gather all output to a variable, say contentVariable, and then
document.getElementById("imageContainer").innerHTML = contentVariable;
note:
It's bad practice to use document.write and even innertml for appending elements to dom. use document.createElement and element.appendChild for dom manupilation.
i have a problem with this code:
var par = [];
$('a[name]').each(function() {
if (($(this).attr('name')).indexOf("searchword") == -1) {
par.push($(this).attr('name'));
$('.content').empty();
for (var i = 0; i < par.length; i++) {
$(".content").append('<a id="par" href="#' + par[i] + '">' + par[i] + '</a><br />');
}
}
});
It causes ie and firefox to popup the warning window "Stop running this script". But it happens only when there is a very very large amount of data on page. Any ideas how to fix it?
Your code should look like this:
var par = [];
$('a[name]').each(function() {
if (($(this).attr('name')).indexOf("searchword") == -1) {
par.push($(this).attr('name'));
}
});
$('.content').empty();
for (var i = 0; i < par.length; i++) {
$(".content").append('<a id="par" href="#' + par[i] + '">' + par[i] + '</a><br />');
}
There is no reason for the second loop to be inside the first - that will just cause a lot of unneeded work.
You can make this code a bit simpler by removing the par array and the second loop, and just creating the content inside the first loop:
$('.content').empty();
$('a[name]').each(function() {
var name = $(this).attr('name');
if (name.indexOf("searchword") == -1) {
$(".content").append('<a id="par" href="#' + name + '">' + name + '</a><br />');
}
});
Browsers run all javascript (and most page interaction) on a single thread. When you run a long loop like this with no interruptions, the UI is totally frozen. You should try to make your algorithm have to do less, but in case that's not possible you can use this trick where you do a bit of work, then pause and give the browser control of the UI thread for a bit, then do more work.
var $targets = $('a[name]');
var current = 0;
var i = 0;
function doSomeWork() {
if (i == $targets.length) return;
var $t = $targets[i];
if (($t.attr('name')).indexOf("searchword") == -1) {
par.push($t.attr('name'));
$('.content').empty();
for (var i = 0; i < par.length; i++) {
$(".content").append('<a id="par" href="#' + par[i] + '">' + par[i] + '</a><br />');
}
}
i++;
window.setTimeout(arguments.callee, 0);
}
This does one iteration of your loop in a function before yielding. It might be a good idea to do more than just one in a function call, but you can experiment with that. An article on this idea: http://www.julienlecomte.net/blog/2007/10/28/