Javascript array display buttons on each click - javascript

HTML and JS....I need the array values to be displayed one by one on each click of the "create new button" button. Right now when I click it displays each button in the array???
<div class="container">
<button onClick="myPar()">Directions</button>
<button onClick="make()">Create New Button</button>
</div>
<script>
function myPar() {
var pgp = document.createElement("p");
var txt = document.createTextNode('Click on the "Create New Button" to reveal up to 10 links!!!');
pgp.appendChild(txt);
document.body.appendChild(pgp);
}
function make(){
sit = new Array("kilroerock.com","ultimateguitar.com","premierguitar.com","jhspedals.com","sweetwater.com","guitarcenter.com","musiciansfriend.com","patriots.com","bostonceltics.com")
for (i=0;i<=sit.length-1;i++){
var btn = document.createElement("input");
btn.setAttribute("value",sit[i]);
btn.setAttribute("type","button");
btn.setAttribute("style","background:#1B0D0D;color:white");
btn.setAttribute("onClick","document.location='http://www." + sit[i] + "'")
document.body.appendChild(btn);
}
}
</script>

Are you expecting something like this
Here s working example
https://plnkr.co/edit/juTx9sEZ4PhAoDrb2uHM?p=preview
function buttonClick(){
var length = sit.length;
if(i<length){
var btn = document.createElement("input");
btn.setAttribute("value",sit[i]);
btn.setAttribute("type","button");
btn.setAttribute("style","background:#1B0D0D;color:white");
btn.setAttribute("onClick","document.location='http://www." + sit[i] + "'")
document.body.appendChild(btn);
i++;}
}

You are iterating the whole array on every click. Instead of the for loop just hold a currentIndex variable outside of the function, then on each click get the sit[currentIndex], use it per your need and afterwards raise the currentIndex by 1.
var currentIndex = 0;
sit = new Array("kilroerock.com","ultimateguitar.com","premierguitar.com","jhspedals.com","sweetwater.com","guitarcenter.com","musiciansfriend.com","patriots.com","bostonceltics.com")
function make(){
if ( currentIndex < sit.length )
{
var btn = document.createElement("input");
btn.setAttribute("value",sit[currentIndex]);
btn.setAttribute("type","button");
btn.setAttribute("style","background:#1B0D0D;color:white");
btn.setAttribute("onClick","document.location='http://www." + sit[currentIndex] + "'")
document.body.appendChild(btn);
currentIndex++;
}
}
Here is a working example.

Simplest route based on your existing code is to implement a "counter".
// Initialize the counter outside of all functions, set to zero
var buttonIndex = 0;
function myPar() {
var pgp = document.createElement("p");
var txt = document.createTextNode('Click on the "Create New Button" to reveal up to 10 links!!!');
pgp.appendChild(txt);
document.body.appendChild(pgp);
}
function make() {
sit = new Array("kilroerock.com", "ultimateguitar.com", "premierguitar.com", "jhspedals.com", "sweetwater.com", "guitarcenter.com", "musiciansfriend.com", "patriots.com", "bostonceltics.com")
// Only add the button if within the array length
if (buttonIndex < sit.length) {
var btn = document.createElement("input");
// Modify this line to use buttonIndex, not i
btn.setAttribute("value", sit[buttonIndex]);
btn.setAttribute("type", "button");
btn.setAttribute("style", "background:#1B0D0D;color:white");
// Modify this line to use buttonIndex, not i
btn.setAttribute("onClick", "document.location='http://www." + sit[buttonIndex] + "'")
document.body.appendChild(btn);
// Increment the buttonIndex
buttonIndex++;
}
}
<div class="container">
<button onClick="myPar()">Directions</button>
<button onClick="make()">Create New Button</button>
</div>

Related

Creating buttons with JS that keeps variable upon creation

I'm creating a HTML table by using JavaScript.
I want add button to the cell with index 5 on each row.
The console.log(i) before the btn.onclick... writes the value of i but when the different buttons are pressed all the outputs are the same and are always 10.
I guess this is because the variable in the function gets updated.
How do you make it so that the button on each row outputs the value of i when the button is "created"
Take a look at my code
var tableRef = document.getElementById("my_table").getElementsByTagName("tbody")[0];
var i;
for (i = 0; i < 10; i++) {
var newRow = tableRef.
newCell = newRow.insertCell(5);
btn = document.createElement('input');
btn.type = "button";
btn.className = "btn";
btn.value = "My button";
console.log(i);
btn.onclick = function() {
console.log(i);
};
newCell.appendChild(btn);
}
Lets follow the JavaScript execution step by step.
You get access to the table
You create the loop which iterates from 0 to 9 (10 steps)
On each step you create the button and assign listener function to the onclick event.
The listener function keep reference to the i variable.
When you loop reach the end
All your elements have rendered to the screen and buttons are available
At this moment i variable is equal to 9.
You click a button.
After clicking the button your function go to the i variable and fetch the value.
The i value is equal to 9 and therefore it prints 9.
To fix this you can move var i; to the loop statement and replace var with let.
See example below
var tableRef = document.getElementById("my_table").getElementsByTagName("tbody")[0];
for (let i = 0; i < 10; i++) { // Use let here
var newRow = tableRef.
newCell = newRow.insertCell(5);
btn = document.createElement('input');
btn.type = "button";
btn.className = "btn";
btn.value = "My button";
console.log(i);
btn.onclick = function() {
console.log(i);
};
newCell.appendChild(btn);
}
For more information you can read the article
I hope this helps you

How to exchange counter after delete field using plain javascript

I'm new in javascript. i have a JS function that add and remove input fields. its working fine with my JS function. But I want when delete a field its Id looks like:
I have
no. 1
no. 2
no. 3
After Delete 2:
no. 1
no. 2
already i got this answer:
Reset JavaScript Counter after Deleting a field
But i want it with plain javascript. Can anyone help?
<script>
var count = 1;
function add_new(){
count++;
var div1 = document.createElement('div');
div1.id = count;
var delLink = '<button type="button" onclick="deleteLink('+count+')" class="btn btn-primary">Delete</button>';
div1.innerHTML = document.getElementById('add_link1').innerHTML+delLink;
document.getElementById('add_link').appendChild(div1);
document.getElementById("input_link1").id = count;
document.getElementById("input_link2").id = count;
document.getElementById("input_link3").id = count;
}
function deleteLink(eleId){
var ele = document.getElementById(eleId);
var par = document.getElementById('add_link');
par.removeChild(ele);
}
</script>
After deleting an element call the following function to reset Id of existing elements and also reduce the count.
function reset_counter(deletedCount) {
for (var impactedElementId = deletedCount + 1; impactedElementId < count; impactedElementId++) {
var currentElement = document.getElementById(impactedElementId);
currentElement.id = impactedElementId - 1;
var button = currentElement.firstChild;
button.innerHTML = 'Delete ' + currentElement.id;
button.setAttribute('onclick', 'deleteLink(' + currentElement.id + ')');
}
count--;
}
The full code is available here: AddDeleteElements Sample Code

after adding elements through button why clicking on list items will not change the heading?

I have a simple application. There is a list, clicking on an item in the list will update the header to match the text of the list item. There is also a button to add new items to the list.
Here is my code
var counter = 1;
var MyList = document.querySelector("#mylist"); // mylist is id of ul
var heading = document.querySelector("#heading"); // heading is id of header
var btn = document.querySelector(".btn");
var list = document.querySelectorAll("#mylist li");
for (i = 0; i < list.length; i++) {
list[i].addEventListener("click", changeHead);
}
function changeHead() {
heading.innerHTML = this.innerHTML;
}
btn.addEventListener("click", addRecord);
function addRecord() {
MyList.innerHTML += "<li>something New " + counter + "</li>";
counter++;
}
<h1 id="heading">Hii,Bhushan</h1> <button class="btn">Add New</button>
<ul id="mylist">
<li>bhushan dhage</li>
<li>vishal Ambhore</li>
<li>Ravi kauthale</li>
<li>manik jadhav</li>
</ul>
Clicking on list items seems to work correctly but when I add a new list item and click on it the header does not update. Do you know why this is the case?
Thank you.
This happens because you only add your eventListener once, you have to add it to the new item each time you add one.
If I were you rather than using innerHTML I would use createElement and then append your new element to the list. This has the added advantage of being able to add your eventListener to the new li while you're making it.
In an HTML document, the document.createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognized.
Here is the code, the only changes are in the addRecord function
var counter = 1;
var MyList = document.querySelector("#mylist"); // mylist is id of ul
var heading = document.querySelector("#heading"); // heading is id of header
var btn = document.querySelector(".btn");
var list = document.querySelectorAll("#mylist li");
for (i = 0; i < list.length; i++) {
list[i].addEventListener("click", changeHead);
}
function changeHead() {
heading.innerHTML = this.innerHTML;
}
btn.addEventListener("click", addRecord);
function addRecord() {
var listItem = document.createElement('li');
var text = document.createTextNode("something New " + counter);
listItem.appendChild(text)
listItem.addEventListener("click", changeHead);
MyList.appendChild(listItem);
counter++;
}
<h1 id="heading">Hii,Bhushan</h1> <button class="btn">Add New</button>
<ul id="mylist">
<li>bhushan dhage</li>
<li>vishal Ambhore</li>
<li>Ravi kauthale</li>
<li>manik jadhav</li>
</ul>
I hope you find this helpful if anything is confusing feel free to ask.
i did a simple change in your code, might help you
var counter = 1;
var MyList = document.querySelector("#mylist"); // mylist is id of ul
var heading = document.querySelector("#heading"); // heading is id of header
var btn = document.querySelector(".btn");
var list = document.querySelectorAll("#mylist li");
MyList.onclick = function(e) {
heading.innerHTML = e.target.innerHTML;
}
btn.addEventListener("click", addRecord);
function addRecord() {
MyList.innerHTML += "<li>something New " + counter + "</li>";
counter++;
}
<h1 id="heading">Hii,Bhushan</h1> <button class="btn">Add New</button>
<ul id="mylist">
<li>bhushan dhage</li>
<li>vishal Ambhore</li>
<li>Ravi kauthale</li>
<li>manik jadhav</li>
</ul>
This might work for you i removed unnecesary functions created an li element rather than changing myList innerHtml. also when new li created a event listener is added to it.
let counter = 1;
myList.forEach(function(element) {
addListener(element);
});
function addListener(element) {
element.addEventListener("click", function() {
heading.innerHTML = element.innerHTML;
});
}
btn.addEventListener("click", function() {
let newLi = document.createElement("LI");
newLi.innerHTML= "Something New" + counter;
addListener(newLi);
counter ++;
MyList.appendChild(newLi);
});

Automatically adding extra space to result and Uncaught TypeError: Cannot read property 'keyCode' of undefined

I am learning JavaScript.
I have created a input and a button. So whenever user type anything in the input it will show in the list item. It is working as expected but the automatic space and console error is bugging me.
Automatic space :- The first result has no space between 1 and Rahul. Whereas other result have space between them. The results are added in list item in two different events.
1) On Enter key press
2) On click on add new button
Console error
document.getElementById('user_input').focus();
function onPress_ENTER()
{
var keyPressed = event.keyCode || event.which;
//if ENTER is pressed
if(keyPressed==13)
{
incre();
keyPressed=null;
}
else
{
return false;
}
}
var count = 0;
onPress_ENTER();
function incre(){
count += 1;
var text = document.createTextNode(count);
var el = document.createElement("li");
//get text from input box and create node
var user_input = document.getElementById('user_input').value;
var user_input_node = document.createTextNode(user_input);
//create element node span and add user input inside span
var user_el = document.createElement('span');
user_el.appendChild(user_input_node);
//id of list item element
var id_el = document.getElementById('list_item');
//append counter inside the li
el.appendChild(text);
el.appendChild(user_el);
id_el.appendChild(el);
document.getElementById('user_input').value = " ";
document.getElementById('user_input').focus();
}
<input type="text" id="user_input" onkeypress="onPress_ENTER()">
<input type="button" onclick="incre()" value="add new">
<ul id="list_item">
</ul>
Your issue is on how you organized your code.
You can call the function onPress_ENTER only at document ready.
For the event I suggest you to pass it directly in the inline call.
Instead of keyPressed=null; you can use preventDefault.
In order to reset the input field you can write:
// reset input
document.getElementById('user_input').value = "";
document.getElementById('user_input').focus();
but, when you need to add this to the list you can change this line:
var user_input = document.getElementById('user_input').value;
to:
var user_input = " " + document.getElementById('user_input').value;
The example:
// when document is ready
document.addEventListener('DOMContentLoaded', function(e) {
document.getElementById('user_input').focus();
onPress_ENTER(e); // this is useless.....
});
// global func and var
function onPress_ENTER(e) {
var keyPressed = e.keyCode || e.which;
//if ENTER is pressed
if (keyPressed == 13) {
e.preventDefault();
incre();
}
}
var count = 0;
function incre() {
count += 1;
var text = document.createTextNode(count);
var el = document.createElement("li");
//get text from input box and create node
var user_input = " " + document.getElementById('user_input').value;
var user_input_node = document.createTextNode(user_input);
//create element node span and add user input inside span
var user_el = document.createElement('span');
user_el.appendChild(user_input_node);
//id of list item element
var id_el = document.getElementById('list_item');
//append counter inside the li
el.appendChild(text);
el.appendChild(user_el);
id_el.appendChild(el);
// reset input
document.getElementById('user_input').value = "";
document.getElementById('user_input').focus();
}
<input type="text" id="user_input" onkeypress="onPress_ENTER(event)">
<input type="button" onclick="incre()" value="add new">
<ul id="list_item">
</ul>
here: var count = 0; onPress_ENTER(); you call a function without event. You need to remove this call
look at jsfiddle
document.getElementById('user_input').focus();
function onPress_ENTER()
{
var keyPressed = event.charCode || event.which;
//if ENTER is pressed
if(keyPressed==13)
{
incre();
keyPressed=null;
}
else
{
return false;
}
}
var count = 0;
function incre(){
count += 1;
var text = document.createTextNode(count);
var el = document.createElement("li");
//get text from input box and create node
var user_input = document.getElementById('user_input').value;
var user_input_node = document.createTextNode(user_input);
//create element node span and add user input inside span
var user_el = document.createElement('span');
user_el.appendChild(user_input_node);
//id of list item element
var id_el = document.getElementById('list_item');
//append counter inside the li
el.appendChild(text);
el.appendChild(user_el);
id_el.appendChild(el);
document.getElementById('user_input').value = " ";
document.getElementById('user_input').focus();
}

getElementsByClassName only getting one item

I am trying to save an input box and when using document.getElementsByClassName The action only works on the last item.
I have created a fiddle
http://jsfiddle.net/ktcle/6P8yx/2/
If you enter text in the first textbox and save it returns blank, however it you enter text in the second textbox it returns for both save buttons
var fileNameToSaveAs = document.getElementById("tlt").innerHTML;
var myDivObj = document.getElementById("tlt").innerHTML;
var items = document.getElementsByClassName('notesApp');
for (var i = 0; i < items.length; i++) {
var textToWrite = items[i].value
//alert(textToWrite);
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
}
I need each box to save the correct text input
thanks
There are 2 mistakes:
As #xxx pointed out you have 'notesppp' instead of 'notesApp' in the class attribute.
More importantly, you are replacing textFileAsBlob in the for loop instead of appending to it.
See the section on Building Blobs for appending to blobs here:
https://www.inkling.com/read/javascript-definitive-guide-david-flanagan-6th/chapter-22/blobs
var textToWrite = ""
for (var i = 0; i < items.length; i++) {
textToWrite += items[i].value
//alert(textToWrite);
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
}
Try with a While:
var allSuccess = document.getElementsByClassName("btn btn-lg btn-success");
while (allSuccess.length>0) {
allSuccess[0].disabled = true;
allSuccess[0].className = "btn btn-lg";
allSuccess = document.getElementsByClassName("btn btn-lg btn-success");
}
The two buttons do the same things when clicked.
Getting the second textarea's content.
so give a param to saveTextAsFile the textarea's id you need.
And get the correct content you want.
<div>
<textarea id="inputTextToSave" class="notesppp"></textarea>
<button onclick="saveTextAsFile('inputTextToSave')" class="btn">Save Notes</button>
</div>
<div>
<textarea id="inputsecondbox" class="notesApp" ></textarea>
<button onclick="saveTextAsFile('inputsecondbox')" class="btn">Save Notes</button>
</div>
function saveTextAsFile(textId)
{
var fileNameToSaveAs = document.getElementById("tlt").innerHTML;
var myDivObj = document.getElementById("tlt").innerHTML;
// changed
var item = document.getElementsById(textId);
var textToWrite = item.value;
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
// changed
.....
}

Categories

Resources