I am working with javascript and jquery. I want to be able to display a buttom, some text, and/or really any html elements or components as many times as the loop allows. I am able to loop through and print alert statements
function LoopTest() {
var i=0;
var stop=5;
for (i=0;i<5;i++)
{ alert("count: " + i); }
}
Simple enough. This would give me 5 alert statements, but instead of using alert statements, I want to be able to display a button or some text or any other html elements. So I would get five buttons displayed on an html page. Is this possible? I'm actually using a .foreach function but for ease of use, a regular for loop would suffice for now. I want to be able to do this on button click (i.e., the function that has the loop starts running once I click a button) also. I'm just not sure really how to accomplish this. Any help would be greatly appreciated. Thanks in advance.
With vanilla Javascript (without using jQuery):
You can use document.createElement to create any type of element you want on the page. Here's the above loop creating <INPUT TYPE='BUTTON'> elements in a <div> with an id of test:
function LoopTest() {
var i=0;
var stop=5;
for (i=0;i<5;i++) {
var v = document.createElement('input');
v.type="button";
v.value="Button " +i;
document.getElementById('test').appendChild(v);
}
}
(In general, using document.write has been considered a bad practice for a while now.)
With jQuery, you can do:
for (i=0;i<5;i++) {
var btn = $("<button/>");
btn.text('Button '+i);
$('#test').append(btn);
}
You can use innerHTML field to add any html content into container on you page.
<script>
function LoopTest()
{
var i=0;
var stop=5;
for (i=0;i<5;i++)
{
document.getElementById("container").innerHTML += "<button>button</button>"
}
}
</script>
...
<div id="container"></div>
Refer: document.write(), Javascript events
<html>
<head>
<script>
function LoopTest() {
var i=0;
var stop = 5;
for (i=0;i<5;i++)
{
document.write('<p>' + i + '</p>'); // This writes the number in a paragraph
}
}
</script>
</head>
<body>
<!--
Here onclick event is used to recognize the click event,
which is fired when the user clicks the button,
this calls the LoopTest() function which generates 5 paragraphs with numbers
-->
<button onclick="LoopTest()">Click to generate content!</button>
</body>
</html>
This is a solution : http://jsfiddle.net/leojavier/gbuLykdj/
<div class="container">
<button class="trigger">Trigger</button>
</div>
JS
$('.trigger').on('click', function(){
LoopTest();
});
function LoopTest() {
var i=0;
var stop=5;
for (i=0;i<5;i++){
$('body').append('<button class="trigger">Trigger No. ' + i + '</button>')
}
}
Related
I've viewed a couple of the posts in here regarding this topic but not quite working for my situation. I'm using Tampermonkey userscript manager. I want to hide a bunch of div's after the page is fully loaded. I've tested the code below on the console of the page and it works.
document.getElementsByClassName('promotions-personalized-offers-ui-single-offer')[0].style.display='none';
This alert also works with the Tampermonkey userscript manager.
window.addEventListener("load", function(){
// code goes below
alert("hello world");
});
However, the following code is not working. Neither the div or the alert is working in this situation.
window.addEventListener("load", function(){
// ....
document.getElementsByClassName('promotions-personalized-offers-ui-single-offer')[0].style.display='none';
alert("it's working");
});
By the way, I'm a newbie to Javascript so any help is much appreciated.
You currently only hide the first ([0]) div. You need to iterate over all elements to hide them.
I'd suggest using document.querySelectorAll because it's easily iterable:
window.addEventListener("load", function(){
document.querySelectorAll('promotions-personalized-offers-ui-single-offer')
.forEach(e => (e.style.display = 'none'));
});
If you must stick to getElementsByClassName, a spread should do the trick:
window.addEventListener("load", function(){
[...document.getElementsByClassName('promotions-personalized-offers-ui-single-offer')]
.forEach(e => (e.style.display = 'none'));
});
Try this:
var x = 3 //number of div elements to remove
window.onload = function() {
for (var i = 0; i < x; i++) {
var elementid = "div" + i.toString(); //ends up as "div1" or "div3"
var div = document.getElementById(elementid)
document.body.remove(div);
}
The divs would need to look like this:
<div id="div1">Content</div>
<div id="div2">Content</div>
<div id="div3">Content</div>
Alternatively, if you're putting the JavaScript code inside a function that's called after the page loads fully, you can just use this:
var x = 3 //number of div elements to remove
function removeDivs() {
for (var i = 0; i < x; i++) {
var elementid = "div" + i.toString(); //ends up as "div1" or "div3"
var div = document.getElementById(elementid)
document.body.remove(div);
}
Then call the function by using removeDivs().
Tampermonkey by default runs when the DOMContentLoaded event is dispatched. https://www.tampermonkey.net/documentation.php#_run_at Based on what you have posted it does not look like you need the event listener at all. Your script would only need one line.
document.getElementsByClassName('promotions-personalized-offers-ui-single-offer')[0].style.display='none';
I'm having some trouble with jQuery in Meteor - I'm just trying to learn so I hope someone could help.
So when #addButton is clicked it will append the div to the .formField and each div created on click will have an unique class, eg formField[1], formField[2] etc
The trouble is when the button is clicked instead of just changing the name of the div only, the div is also added 50 times. I know how dumb it sounds as its a loop, but how would I loop only the div's class on click so each have a different name?
My code is below:
Template.form.events({
'click #addButton': function(event) {
var i;
for (i = 0; i < 50; i++) {
$(".formField").append('<div class="formField['+i+']">.....</div>');
}
return false;
If I understand what you are doing here you don't need a loop. You just need a variable to increment every time the button is clicked. Take your append out of the loop and instead on click increment your variable by one then call an append. No loop necessary.
var i = 0;
Template.form.events({
'click #addButton': function(event) {
i += 1;
$(".formField").append('<div class="formField['+i+']">.....</div>');
}
});
return false;
Do it like this, (i.e. by creating a closure), click run to verify
var uuid = 0;
$('#addButton').on('click', function (event) {
uuid = uuid + 1;
$(".formField").append('<div class="formField[' + uuid + ']">Form' + uuid + '</div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="formField"></div>
<input type="button" value="Add New" id="addButton"></input>
I'm trying to take text as input from user and split into array and pass it.
<textarea id="texty">
</textarea>
<input type="button" onclick="funky()" />
<script type="text/javascript">
var str;
var array;
var ACL1;
var ACL2;
function funky() {
str = document.getElementById('texty').value;
array = str.split(' ');
}
for (var i = 0; i < array.length; i++) {
var xi = array[i];
if (xi === "ACL") {
ACL1 = array[i + 1];
ACL2 = array[i + 2];
}
}
I'm again using that variables ACL1 and ACL2 in some other place in the same page using this piece of code
<script type="text/javascript">
document.write(+ ACL1 + "<br>");
</script>
<script type="text/javascript">
document.write(+ ACL2 + "<br>");
</script>
Do anybody know where I'm going wrong?
All your funky() function does is split the string into an array and nothing more - you need to make your for loop part of funky() and see what happens.
You assign a value to array when the button is clicked.
You try to process that data into ACL1 and ACL2 and write them to the page while the document loads.
The button won't be clicked before the document loads.
Move the for loop inside the funky function
Get rid of your document.write scripts.
Replace them with div elements (or some other container that is more semantically appropriate).
Modify the funky function to add the content to the page once it is populated the variables
Find the element you want to put the content in (e.g. with document.getElementById or document.querySelector)
Put the content inside it (e.g. with document.createTextNode and document.appendChild
My JavaScript code is:
<script type="text/javascript">
var current = 0;
var cars = new Array(5);
cars[0] = "Audi";
cars[1] = "Bentley";
cars[2] = "Mercedes";
cars[3] = "Mini";
cars[4] = "BMW";
document.getElementById("addCarBtn").onclick = function () {
if (!(current > cars.length - 1)) {
document.getElementById("carsDiv").innerHTML += cars[current] + "<br />";
current++;
}
}
</script>
I want to display the value of each array item one by one on button click the div.
But when i click the button, the array[0] i.e "Audi" is displayed but just for fraction of seconds. then it disappears and only the button is visible.
You can use a loop like:-
for(var i=0; i< cars.length;i++)
{
alert(cars[i]);
}
//It will show alert 5 times. You'll need to click through ok to traverse all array elements.
//I think it is what you're thinking, or have I interpreted it wrong.
// I'm assuming you're completely new to javascript then on your button write onclick="yourFuncName();"
function YourfuncName()
{
//Initailze your array here, like you have done or like kamituel has done
// then just print each array element one by one
for(var i=0; i< cars.length;i++)
{
alert(cars[i]);
}
}
How about the every method?
cars.every( function(c) {
alert("car: " + c);
});
You're almost there. Since the JS code was located before the HTML, the button element still doesn't exist. Best just wrap the code with window.onload and it should work:
window.onload = function() {
document.getElementById("addCarBtn").onclick = function() {
if (!(current > cars.length - 1)) {
document.getElementById("carsDiv").innerHTML += cars[current] + "<br />";
current++;
}
}
};
Live test case.
Edit: just noticed your button doesn't have type. This means that some browsers might make it a submit button by default, which will cause a page reload. To avoid it, make it a plain button:
<button id="addCarBtn" type="button">
I have to print 10 values dynamically in javascript using for loop. Here I take label for printing.
Now when I click on particular text on label I can show one alert with that text name,
Any One help me How to do this.
<html>
<head>
<script type = "text/javascript">
var x = "";
function checkCookie(){
var arr = new Array("One","Two","Three");
for(var i=0; i<arr.length; i++) {
x = x + arr[i] + "<br>" + "<br>";
document.getElementById("idval").innerHTML = x;
}
}
function getItem(){
// here i want to display the selected label item
}
</script>
</head>
<body onload = "checkCookie()">
<label id = "idval" onclick = "getItem()"> </label>
</body>
</html>
Not at all clear from your question description what it is you need. If what you're wanting is to dynamically create labels, and have access to their onclick events; have a look at the Javascript functions appendChild and setAttribute. I've created a JSfiddle which demonstrates what you might need:
function createLabels() {
for(var i=0; i<10; i++) {
var label = document.createElement('label');
label.innerHTML = "item " + i;
label.onclick = onClick;
document.body.appendChild(label);
}
}
function onClick(e){
alert(e.srcElement.innerHTML)
}
http://jsfiddle.net/R4abH/2/
Edit 1 : Adding onclick attributes is considered bad practise. Reworked answer using event listeners instead.
Edit 2 : As per Benjamin Gruenbaum's comment below, AddEventListener does not seem to be supported by IE (please see MSIE and addEventListener Problem in Javascript?). Reworked jsfiddle to use onclick instead, as per dystroy's suggestion.