getElementsByClassName only getting one item - javascript

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
.....
}

Related

Check box won't append

So the HTML has these elements, there can be a random number of them. I would simply like to create a check box, and add it to each element with the class name "username".
So when a new element with the class "username" gets created or when the page is opened. It'll add a check box to it.
Here's my script.
var chec = document.createElement("div"); //Creates the div..
chec.innerHTML = '<input type="checkbox" value="test">'; //Create checkbox
var addc = document.querySelector("span[class='username']") // username Element.
var i;
for (i = 0; i < addc.length; i++) {
chec += addc[i];
}
It doesn't add the check boxes. Can someone help me understand why and possibly help me with my script.
var addc = document.querySelectorAll("span.username") // Get all elements with class "username"
for (var i = 0; i < addc.length; i++) {
var div = document.createElement("div");
var check = document.createElement("input");
check.type = "checkbox";
check.value = "test";
div.appendChild(check);
addc[i].appendChild(div);
}
<span class="username"></span>
<span class="username"></span>
<span class="username"></span>

focus is not working on textarea

I am creating a page in which a user can add a question and its solution, he can delete the problem and can also edit it dynamically using DOM in javascript. I want that whenever user clicks on edit button the textbox which appears get autofocus.
This the javascript code of my page...
var questionText;
var answerText;
var questionArray=[];
var answerArray=[];
var i=0;
var j=10000;
function addProblem(){
var body = document.getElementsByTagName('body')[0];
questionText = document.getElementById('questionId').value;
answerText = document.getElementById('answerId').value;
questionArray.unshift(questionText);
answerArray.unshift(answerText);
var myContainer = document.getElementById('container');
var myDiv = document.createElement("div");
var questionLogo = document.createElement("p");
questionLogo.id = "questionLogo";
var textNode = document.createTextNode("Question:");
var question = document.createElement("p");
question.id = "question";
var questionDetail = document.createTextNode(questionArray[0]);
var deleteButton = document.createElement("button");
deleteButton.innerHTML = "Delete";
deleteButton.id = i;
var editButton = document.createElement("button");
editButton.innerHTML = "Edit";
editButton.id = j;
var answerLogo = document.createElement("p");
answerLogo.id = "answerLogo"
var ansTextNode = document.createTextNode("Answer: ");
var answer = document.createElement("p");
answer.id = "answer";
var answerDetail = document.createTextNode(answerArray[0]);
var mybr = document.createElement("br");
if(i==0){
myContainer.appendChild(myDiv);
myDiv.appendChild(questionLogo);
questionLogo.appendChild(textNode);
questionLogo.appendChild(question);
question.appendChild(questionDetail);
myDiv.appendChild(answerLogo);
answerLogo.appendChild(ansTextNode);
answerLogo.appendChild(answer);
answer.appendChild(answerDetail);
answerLogo.appendChild(mybr);
myDiv.appendChild(deleteButton);
myDiv.innerHTML += ' ';
myDiv.appendChild(editButton);
}
else if (i > 0)
{
myContainer.insertBefore(myDiv,myContainer.firstChild);
myDiv.appendChild(questionLogo);
questionLogo.appendChild(textNode);
questionLogo.appendChild(question);
question.appendChild(questionDetail);
myDiv.appendChild(answerLogo);
answerLogo.appendChild(ansTextNode);
answerLogo.appendChild(answer);
answer.appendChild(answerDetail);
answer.appendChild(mybr);
myDiv.appendChild(deleteButton);
myDiv.innerHTML += ' ';
myDiv.appendChild(editButton);
}
i++;
j++;
myDiv.childNodes[7].addEventListener("click", function(){
var deleteElement = document.getElementById(this.id);
deleteElement.parentNode.parentNode.removeChild(deleteElement.parentNode);
});
myDiv.childNodes[9].addEventListener("click",function(){
var editElement = document.getElementById(this.id);
var quesEdit = editElement.parentNode.childNodes[1];
var quesEditText = quesEdit.innerHTML;
var ansEdit = editElement.parentNode.childNodes[4];
var ansEditText = ansEdit.innerHTML;
var editDiv1 = document.createElement("div");
editDiv1.id = "editDiv1"
var quesTextArea = document.createElement("textarea");
quesTextArea.innerHTML += quesEditText;
quesTextArea.focus();
var saveButton1 = document.createElement("button");
saveButton1.innerHTML = "Save";
editDiv1.appendChild(quesTextArea);
editDiv1.innerHTML += ' ';
editDiv1.appendChild(saveButton1);
quesEdit.parentNode.replaceChild(editDiv1,quesEdit);
var editDiv2 = document.createElement("div");
editDiv2.id = "editDiv2"
var ansTextArea = document.createElement("textarea");
ansTextArea.innerHTML += ansEditText;
var saveButton2 = document.createElement("button");
saveButton2.innerHTML = "Save";
editDiv2.appendChild(ansTextArea);
editDiv2.innerHTML += ' ';
editDiv2.appendChild(saveButton2);
ansEdit.parentNode.replaceChild(editDiv2,ansEdit);
});
}
I have tried to focus the textarea using
quesTextArea.focus();
but its not working where questextArea is the name of the textarea. Please help how i can do it.
For the element could be got focused, it must be in the DOM when you invoke focus on it. You should invoke focus function after replaceChild function
editDiv1.appendChild(quesTextArea);
editDiv1.appendChild(saveButton1);
quesEdit.parentNode.replaceChild(editDiv1,quesEdit);
quesTextArea.focus();
I've created a simple sample as below link, you could check it
https://jsfiddle.net/pd9c6c7a/3/
Add autofocus attribute to the textarea element. So that whenever it is appended to the DOM, will get cursor activated in it.
The 'textarea' has not been added to window to be shown, an element must be part of the document object tree. In case that didn't work, add a 50ms delay.
setTimeout(function(){e.focus();}, 50);
Try the following approach:
var body=document.getElementsByTagName('body')[0];
var quesTextArea=document.createElement("textarea");
var button=document.createElement("button");
button.innerHTML = "click Me";
button.addEventListener("click",function(e){
e.preventDefault();
quesTextArea.focus();
});
body.appendChild(quesTextArea);
body.appendChild(button);
<html>
<body>
<body>
</html>
Try to add preventDefault.
var div = document.getElementById('parent');
var txt = document.createElement('textarea');
div.appendChild(txt);
txt.focus();
<html>
<head></head>
<body>
<div id="parent">
<input type="text" value="" />
</div>
</body>
</html>
The element must be in the DOM when you invoke the focus function. Move your focus() function after the appendChild() is invoked.
quesTextArea.innerHTML += quesEditText;
var saveButton1=document.createElement("button");
saveButton1.innerHTML="Save";
editDiv1.appendChild(quesTextArea);
quesTextArea.focus();

Javascript array display buttons on each click

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>

How to remove an item in an array using an onclick function?

In this code, I am trying to push items into the array and then removing them.
If you see below, the create button will give me a blank input and a button that stores it into an array. After it is pushed into the array, the view button goes through the array and displays all the items with the buttons "edit" and "delete" beside it. This is where my problem lies... for each item that is put into the array, it displays it on the Html and has its own buttons. How do I delete that item from the array when I click on a specific delete button?
//variables
var create = document.getElementById("create");
var view = document.getElementById("view");
var display = document.getElementById("display");
var text = document.getElementById("text");
var push = document.getElementById("push");
var arr1 = [];
//create button
create.onclick = function () {
text.style.display = "inline";
push.style.display = "inline";
}
//push button
push.onclick = function () {
arr1.push(text.value);
push.dataset.u_index;
console.log(arr1);
text.value = "";
}
//view button
view.onclick = function () {
for (var i = 0; i < arr1.length; i++) {
var disp = document.createElement("div");
disp.innerHTML = arr1[i];
display.appendChild(disp);
var edit = document.createElement("button");
var edit_t = document.createTextNode("Edit");
disp.appendChild(edit);
edit.appendChild(edit_t);
var del = document.createElement("button");
var del_t = document.createTextNode("Delete");
disp.appendChild(edit);
edit.appendChild(edit_t);
disp.appendChild(del);
del.appendChild(del_t);
}
//del button
del.onclick = function () {
}
}
}
You need some way of identifying the element you want to delete so it can be tied to the delete function. Here's some code that shows one possible way using data attributes.
//variables
var create = document.getElementById("create");
var view = document.getElementById("view");
var display = document.getElementById("display");
var text = document.getElementById("text");
var push = document.getElementById("push");
var results = document.getElementById("results");
var arr1 = [];
//create button
create.onclick = function() {
text.style.display = "inline";
push.style.display = "inline";
}
//push button
push.onclick = function() {
arr1.push(text.value);
push.dataset.u_index;
console.log(arr1);
text.value = "";
}
//view button
view.onclick = function() {
for (var i = 0; i < arr1.length; i++) {
var disp = document.createElement("div");
disp.innerHTML = arr1[i];
results.appendChild(disp);
var edit = document.createElement("button");
var edit_t = document.createTextNode("Edit");
disp.appendChild(edit);
edit.appendChild(edit_t);
var del = document.createElement("button");
var del_t = document.createTextNode("Delete");
disp.appendChild(edit);
edit.appendChild(edit_t);
disp.appendChild(del);
del.appendChild(del_t);
del.setAttribute('data-item-index', i);
//set onclick fn for del button
del.onclick = function() {
var itemIndex = this.getAttribute('data-item-index');
arr1.splice(itemIndex, 1);
console.log(arr1);
results.innerHTML = '';
view.click();
};
}
}
<div id='display'>
<button id="create">Create</button>
<div>
<input type="text" id='text'>
<button id='push'>Push</button>
</div>
<button id='view'>View</button>
<div id='results'></div>
</div>

How to space my checkboxes and the text associated with them

I have these check boxes that are created with a javascript function:
I would like the text to appear to the right of the checkbox and all of the text to be on one line.
Here is the javascript function and the html:
function receiveAnswer(response) {
// var aSeats = document.getElementById("aSeats");
// aSeats.options.length = 0;// clear it out
//
// for (var i = 0; i < response.aSeats.length; i++) { // add the items back in
// var option = aSeats.appendChild(document.createElement("option"));
// option.value = i;
// option.appendChild(document.createTextNode(response.aSeats[i]));
// }
var aSeats = document.getElementById("aSeats");
while (aSeats.childNodes.length > 0) { // clear it out
aSeats.removeChild(aSeats.childNodes[0]);
}
for (var i = 0; i < response.aSeats.length; i++) { // add the items back in
var input = aSeats.appendChild(document.createElement("input"));
input.value = i;
input.type = "checkbox";
var br = aSeats.appendChild(document.createElement("br"));
input.appendChild(document.createTextNode(response.aSeats[i]));
var br = aSeats.appendChild(document.createElement("br"));
var br = aSeats.appendChild(document.createElement("br"));
var br = aSeats.appendChild(document.createElement("br"));
var br = aSeats.appendChild(document.createElement("br"));
var br = aSeats.appendChild(document.createElement("br"));
}
}
html code:
<div name="aSeats" id="aSeats">
<input type="checkbox">
</div>
Why not use jQuery.
Check working example http://jsfiddle.net/FxgYz/
Create a separate div to put the text in and position that div to the side of the input box, something like:
var div = document.createElement("div");
div.style.width = 100;
div.innerHTML = text;
etc.

Categories

Resources