Appending a button using Javascript without using the createElement method - javascript

<script>
var i=0;
var j="";
function app() {
j+=document.getElementById("demo").innerHTML="<button type='button'>Btn+i</button>";
}
</script>
<button type="button" onclick="app()">Add</button>
<div id="demo">
</div>
I am trying to append a button in the div tag every time user clicks add button.
Also I want the added button to be displayed like : Btn 1, Btn2,
Btn3..

A simple concatenation of #demo content and incrementation of a var i:
var i = 0;
function app() {
document.getElementById("demo").innerHTML += "<button type='button'>Btn " +
++i + "</button>";
}
<button type="button" onclick="app()">Add</button>
<div id="demo"></div>

You need to append HTML
var s = 0;
function app(){
s++;
var strHTML = "<button>Btn"+ s+"</button>"
document.getElementById('test').insertAdjacentHTML( 'beforeend', strHTML );
}
See this http://jsfiddle.net/euQ5n/226/

Or make it a little more readable.
<script>
var i = 0;
var j = "";
function makeButton(index) {
var $button = document.createElement('BUTTON');
$button.innerHTML = 'Button ' + index;
$button.onclick = function() {
alert('You clicked button:' + index);
};
return $button;
}
function onAddButtonClick() {
document.getElementById("demo").appendChild(makeButton(i));
i++; // increase number for next time;
}
</script>
<button type="button" onclick="onAddButtonClick()">Add</button>
<div id="demo">
</div>

var i1 = 0;
function app1()
{
var div = document.createElement('div');
div.innerHTML = "<button type='button'>Btn " + (++i1) + "</button>";
for (var child = 0; child < div.childNodes.length; child) {
document.getElementById("demo1").append(div.childNodes[child]);
}
}
var i2 = 0;
function app2() {
document.getElementById("demo2").innerHTML += "<button type='button'>Btn " +
++i2 + "</button>";
}
var d1s = new Date().getTime();
for (var j1 = 0; j1 < 1000; j1++) {
app2();
}
var d1e = new Date().getTime();
console.log((d1e - d1s) / 1000);
var d2s = new Date().getTime();
for (var j2 = 0; j2 < 1000; j2++) {
app1();
}
var d2e = new Date().getTime();
console.log((d2e - d2s) / 1000);
<div id="demo1"></div>
<div id="demo2"></div>
concatenation with innerHtml += is very slow

You need to change .innerHtml += ...
And increase i
var i=0;
function app()
{
j+=document.getElementById("demo").innerHTML+="<button type='button'> Btn"+i+"</button>";
i++;
}
<button type="button" onclick="app()">Add</button>
<div id="demo">
</div>

Related

Counter Using Javascript, HTML & CSS Not Working

Can anyone help me to get this (https://jsfiddle.net/hmatrix/v3jncqac/) code to work?
Inentention: I want to create a counter that increases in increments.
My HTML:
<body onload="incrementCount(10)">
<div class="main_container" id="id_main_container">
<div class="container_inner" id="display_div_id">
</div>
</div>
</body>
My JS:
var counter_list = [10,10000,10000];
var str_counter_0 = counter_list[0];
var str_counter_1 = counter_list[1];
var str_counter_2 = counter_list[2];
var display_str = "";
var display_div = document.getElementById("display_div_id");
function incrementCount(current_count){
setInterval(function(){
// clear count
while (display_div.hasChildNodes()) {
display_div.removeChild(display_div.lastChild);
}
str_counter_0++;
if (str_counter_0 > 99) {
str_counter_0 = 0; // reset count
str_counter_1++; // increase next count
}
if(str_counter_1>99999){
str_counter_2++;
}
display_str = str_counter_2.toString() + str_counter_1.toString() + str_counter_0.toString();
for (var i = 0; i < display_str.length; i++) {
var new_span = document.createElement('span');
new_span.className = 'num_tiles';
new_span.innerText = display_str[i];
display_div.appendChild(new_span);
}
},1000);
}
<body onload="incrementCount(10)">
<div class="main_container" id="id_main_container">
<div class="container_inner" id="display_div_id">
</div>
</div>
</body>
<script>
var counter_list = [10,10000,10000];
var str_counter_0 = counter_list[0];
var str_counter_1 = counter_list[1];
var str_counter_2 = counter_list[2];
var display_str = "";
var display_div = document.getElementById("display_div_id");
function incrementCount(current_count){
setInterval(function(){
// clear count
while (display_div.hasChildNodes()) {
display_div.removeChild(display_div.lastChild);
}
str_counter_0++;
if (str_counter_0 > 99) {
str_counter_0 = 0; // reset count
str_counter_1++; // increase next count
}
if(str_counter_1>99999){
str_counter_2++;
}
display_str = str_counter_2.toString() + str_counter_1.toString() +
str_counter_0.toString();
for (var i = 0; i < display_str.length; i++) {
var new_span = document.createElement('span');
new_span.className = 'num_tiles';
new_span.innerText = display_str[i];
display_div.appendChild(new_span);
}
},1000);
}
</script>
JSFIDDLE: https://jsfiddle.net/v3jncqac/32/
Your onload function cannot find the function because your js is in a different file. you need to add script src on top of html or do it as shown above.

Count amount of times a value is represented

i have some code that takes input numbers and put them into a new array. How can i make it so my alert tells the user how many times the number is represented in the input? Exampel 0,4,4,2,3,4,1 would show "0 appears 1 time, 4 appears 3 times" and so on...I think im close but cant get the final part right...
<!DOCTYPE html>
<html>
<head>
<title>Oppgave 5</title>
<script type="text/javascript">
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showTxt;
}
function showTxt() {
var text = "";
var input = document.getElementById("input").value;
var split = input.split(",");
var newArray = split;
var count = 0;
for (var i = 0; i < newArray.length; i++) {
if (newArray[i] === parseInt(input)) {
count++;
}
alert("Number " + newArray[i] + " appears " + count + " times");
}
text += newArray;
document.getElementById("print").innerHTML = text;
}
</script>
</head>
<body>
<input id="input" type="text">
<button id="btn" type="button">Show</button>
<p id="print"></p>
</body>
</html>
I have changed your showTxt function
function showTxt() {
var text = "";
var input = document.getElementById("input").value;
var split = input.split(",");
var newArray = split;
var count;
for (var i = 0; i < newArray.length; i++) {
count = 0;
for (var j = 0; j < newArray.length; j++) {
if (newArray[i] === newArray[j]) {
count++;
}
}
alert("Number " + newArray[i] + " appears " + count + " times");
}
text += newArray;
document.getElementById("print").innerHTML = text;
}
You could use the method from this gist like so:
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showTxt;
}
function showTxt() {
var text = "";
var input = document.getElementById("input").value;
var split = input.replace(/ /g, '').split(",").sort();
compressArray(split);
}
function compressArray(original) {
var compressed = [];
// make a copy of the input array
var copy = original.slice(0);
// first loop goes over every element
for (var i = 0; i < original.length; i++) {
var myCount = 0;
// loop over every element in the copy and see if it's the same
for (var w = 0; w < copy.length; w++) {
if (original[i] == copy[w]) {
// increase amount of times duplicate is found
myCount++;
// sets item to undefined
delete copy[w];
}
}
if (myCount > 0) {
var a = new Object();
a.value = original[i];
a.count = myCount;
compressed.push(a);
}
}
for (var i = 0; i < compressed.length; i++) {
var message = compressed[i].value + ' appears ' + compressed[i].count + ' times.';
alert(message);
document.getElementById("print").innerHTML += message + '</br>';
}
};
<input id="input" type="text">
<button id="btn" type="button">Show</button>
<p id="print"></p>
Check this out, may be it'll helpful .
<!DOCTYPE html>
<html>
<head>
<title>Oppgave 5</title>
<script type="text/javascript">
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showTxt;
}
function showTxt() {
var text = "";
var input = document.getElementById("input").value;
var split = input.split(",");
var newArray = split;
let countedValues = newArray.reduce(function(obj,val){
if(obj[val])
obj[val] += 1;
else
obj[val] = 1;
return obj
}, {})
for (let value in countedValues ) {
alert("Number " + value + " appears " + countedValues[value] + " times");
}
text = newArray;
document.getElementById("print").innerHTML = text;
}
</script>
</head>
<body>
<input id="input" type="text">
<button id="btn" type="button">Show</button>
<p id="print"></p>
</body>
</html>

using Javascript how to display element one by one on click

how to display element one by one on click using only Javascript, in my example when I click all elements show at once, but i need only one click - one element. I appreciate if you show the simplest way to do if in order to i can understand how it works
$(function() {
var cars = ["audi", "bmw", "volvo"];
var x = "";
var i;
for (i = 0; i <cars.length; i++) {
x += cars[i] + "<br>";
}
document.getElementById("btn").onclick = function() {
document.getElementById("text").innerHTML = x;
}
});
You may update your code as follows. At the very beginnig, your are initializing x with empty string. Then for each click on button, append an element from array with new line tag.
var cars = ["audi", "bmw", "volvo"];
var x = "";
var i = 0;
document.getElementById("btn").onclick = function() {
if( i < cars.length) {
x += cars[i++] + "<br>";
}
document.getElementById("text").innerHTML = x;
}
<p id="text"></p>
<button id="btn">Result</button>
<html>
<script>
var cars = ["audi", "bmw", "volvo"];
var x = "";
var count = 0;
function appendArray(){
if(count<cars.length){
x += cars[count]+ "<br>";
document.getElementById("appendText").innerHTML = x;
count++;
}else{
count = 0;
document.getElementById("appendText").innerHTML = "";
}
}
</script>
<p id="appendText"></p>
<button onclick="appendArray()">Submit</button>
</html>
Here is one solution in vanilla javascript:
var button = document.getElementsByTagName('button')[0];
var i = 0;
function addCar(i) {
var cars = ['audi', 'bmw', 'volvo'];
var paragraph = document.getElementsByTagName('p')[0];
if (i < cars.length) {
var newLine = document.createElement('br');
var newCar = document.createTextNode(cars[i]);
paragraph.appendChild(newLine);
paragraph.appendChild(newCar);
}
}
button.addEventListener('click',function(){addCar(i); i++;},false);
<p></p>
<button>Click for a New Car</button>

How To Apply jQuery CSS Selector

I am trying to apply jquery selector on the div which are dynamically created from javaScript Loop
Div's are created from for loop assign class to each div
minus = textbox1 - textbox2;
var count = 0;
var a;
for (x = textbox1; x >= minus; x--) {
a = count++;
$('body').append('<div class="drag' + a + '" >' + x + '</div>');
}
now I am trying to add the css selector on these but it is not working
var colors = ["#42ae18","#eabc00","#147cc4","#FF6EB4","#ed4329","#8d33aa","#00b971","#e9681b","#a2b3d4","#0b863c","#eabc00","#7027a5","#c83131","#00a1de","#0bc1b6","#FF6EB4","#10a0b6","#FF6EB4","#eedfd3","#362819","#FFD700"];
var i = 0;
$(".drag").each(function(){
$(this).css("color",colors[i]);
if(i == colors.length-1)
{
i = 0;
}
else
{
i++;
}
});
the complete code is given below
$("#submitBtn").click(function(){
var x;
var minus;
var textbox1= new Number($("#value1").val());
var textbox2= new Number($("#value2").val());
var colors = ["#42ae18","#eabc00","#147cc4","#FF6EB4","#ed4329","#8d33aa","#00b971","#e9681b","#a2b3d4","#0b863c","#eabc00","#7027a5","#c83131","#00a1de","#0bc1b6","#FF6EB4","#10a0b6","#FF6EB4","#eedfd3","#362819","#FFD700"];
var i = 0;
$(".drag").each(function(){
$(this).css("color",colors[i]);
if(i == colors.length-1)
{
i = 0;
}
else
{
i++;
}
});
minus=textbox1-textbox2;
var count=0;
var a;
for(x=textbox1;x>=minus;x--){
a=count++;
$('body').append('<div class="drag'+a+'" >' +x+ '</div>');
}
});
You can use attribute starts with selector like following.
var colors = ["#42ae18", "#eabc00", "#147cc4", "#FF6EB4", "#ed4329", "#8d33aa", "#00b971", "#e9681b", "#a2b3d4", "#0b863c", "#eabc00", "#7027a5", "#c83131", "#00a1de", "#0bc1b6", "#FF6EB4", "#10a0b6", "#FF6EB4", "#eedfd3", "#362819", "#FFD700"];
var i = 0;
$("[class^=drag]").each(function () { //change selector here
$(this).css("color", colors[i]);
if (i == colors.length - 1) {
i = 0;
}
else {
i++;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="drag0">!!!!!</div>
<div class="drag1">!!!!!</div>
<div class="drag2">!!!!!</div>
<div class="drag3">!!!!!</div>
<div class="drag4">!!!!!</div>
<div class="drag5">!!!!!</div>
<div class="drag6">!!!!!</div>
<div class="drag7">!!!!!</div>
<div class="drag8">!!!!!</div>

Why does this for loop not display in my div using JavaScript?

I want to display the content in my div but the code won't work. Please show me how to do it.
<!DOCTYPE html>
<html>
<body>
<p id="display"></p>
<script>
var i;
for (i = 0; i < 11; i++) {
var disp = "the number is " + i;
console.log(disp);
}
disp = document.getElementById("display").innerHTML;
</script>
</body>
</html>
How can I get the loop to display my variable in my selected div? Which part of my code is wrong? please help.
Tehre are multiple problems
<p id="display"></p>
<script>
var i;
//initialize the value
var disp = '';
for (i = 0; i < 11; i++) {
//concatenate the value of disp so that new value will be added to the previous content other wise the values will be overwritten
disp += "the number is " + i;
console.log(disp);
}
//assign value of disp to the elemet innerHTML
document.getElementById("display").innerHTML = disp;
</script>
Set the innerHTML inside the for loop.
for (var i = 0; i < 11; i++) {
var disp = "the number is " + i;
document.getElementById("display").innerHTML = disp;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
IF you want to display all the content at once
var disp = ''; // Assign empty string
for (var i = 0; i < 11; i++) {
disp += " the number is " + i; // Concat message
}
document.getElementById("display").innerHTML = disp; // Add into html
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Because you never write anything to your HTML page. You just display it in your console. And later you assign the HTML content of the #display element to the variable disp, which doesn't make any sense:
disp = document.getElementById("display").innerHTML;
This is how it will work
<!DOCTYPE html>
<html>
<body>
<p id="display"></p>
<script>
var i;
for(i=0; i<11; i++){
var disp = "the number is " + i;
// This just writes to the javascript console
console.log(disp);
// This writes in the #display element on your page
document.getElementById("display").innerHTML += disp + '<br>';
}
</script>
</body>
</html>
var i;
for(i=0; i<11; i++){
var disp = "the number is " + i;
console.log(disp);
}
document.getElementById("display").innerHTML = disp;
Something like this should be fine
function createDivs(){
var pContainer = document.getElementById("display");
var i;
for(i = 0; i < 11; i++){
var message = "the number is " + i;
console.log(message);
var element = document.createElement("div");
element.innerHTML = message;
pContainer.appendChild(element);
}
disp = document.getElementById("display").innerHTML;
};
createDivs();

Categories

Resources