using for loop to create html elements - javascript

What is wrong with my code? It is supposed to create input tags in html with using the incoming number (quantity):
// Declare variables
var numberOfGrades = 0;
var NL = "\n";
// Functions
function setQuantity() {
numberOfGrades = document.getElementById("quantity").value;
var inputBox = document.createElement("INPUT");
var BR = document.createElement("br"); // Break line
var gradeNumber = 1;
var gradeText = document.createTextNode("Grade " + gradeNumber + ":");
for (var i = 0; i < numberOfGrades; i++) {
alert(numberOfGrades);
document.getElementById("formDiv").appendChild(BR);
document.getElementById("formDiv").appendChild(gradeText);
document.getElementById("formDiv").appendChild(inputBox);
gradeNumber++;
}
}
body {
font-family: "Open Sans", sans-serif;
}
.container {
width: 100%;
background-color: lightcyan;
padding: 10px;
}
<body>
<h1>Homework and Quiz average calculator</h1>
<p>Please Enter the required information to calcuate</p>
<div class="container" id="formDiv">
<form id="formID">
<p>
<strong>Calculate the average of homework grades</strong>
</p>
How many grades?
<input type="number" id="quantity" name="quantity" min="1" max="10" value="1">
<!--<input onclick="setQuantity()" type="submit" value="Apply">-->
</form>
<button onclick="setQuantity()">APPLY</button>
<br>
</div>
<script src="script.js"></script>
</body>
JSFiddle here

When you call x.appendChild(y) the node y is added as a child from x removing it from where it was if already in the DOM.
For example:
var x = document.createElement("div");
var y = document.createElement("div");
var z = document.createElement("div");
x.appendChild(y);
z.appendChild(y); // now y is not inside x any more, was **moved** to z
If you want to have multiple nodes you need to create them inside the loop.

Related

How can I fix this simple mean calculator so it works and how can I make it so it takes as many numbers as I want?

I am making a mean calculator with HTML, JS, and Jquery. I wasn't sure how to retrieve the number of numbers that are entered so I came up with var numberOfNumbers = $('input').attr('class').length but I don't think it works. What is a better way to collect the number of numbers used to find the mean? Is there anything else wrong with my code? Also how can I make it so that I can enter as many numbers as I want and find the average of them? Thanks.
<!DOCTYPE html>
<html>
<head>
<title>Find Average</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="meancalculator.js"></script>
</head>
<body>
<p>Number 1</p>
<input type="text" id="number1" class="numbers">
<p>Number 2</p>
<input type="text" id="number2" class="numbers">
<p>Number 3</p>
<input type="text" id="number3" class="numbers">
<button>Calculate</button>
<p>The mean is <span></span></p>
</body>
</html>
$(function () {
$('button').click(calculate)
})
var number1 = $('#number1').val()
var number2 = $('#number2').val()
var number3 = $('#number3').val()
var numberOfNumbers = $('input').attr('class').length
function calculate() {
var result = (number1 + number2 + number3) / numberOfNumbers
}
$('span').html(result)
Replace your following code :
var numberOfNumbers = $('input').attr('class').length
to:
var numberOfNumbers = $('.numbers').length
A couple of things:
You are taking input field values outside of calculate function. By that time numbers may not have entered. Same goes for displaying results. Move these lines inside calculate function.
Use $('input.numbers').length to get count of input elements having class numbers
Read the numeric values with + in prefix as +$('#number1').val()
Here is your modified code:
<!DOCTYPE html>
<html>
<head>
<title>Find Average</title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="meancalculator.js"></script>
</head>
<body>
<p>Number 1</p>
<input type="text" id="number1" class="numbers">
<p>Number 2</p>
<input type="text" id="number2" class="numbers">
<p>Number 3</p>
<input type="text" id="number3" class="numbers">
<button>Calculate</button>
<p>The mean is <span></span></p>
</body>
</html>
<script>
$(function () {
$('button').click(calculate)
})
function calculate() {
var number1 = +$('#number1').val()
var number2 = +$('#number2').val()
var number3 = +$('#number3').val()
var numberOfNumbers = $('input.numbers').length
var result = (number1 + number2 + number3) / numberOfNumbers
$('span').html(result)
}
</script>
Another way to approach the problem is just to have one input into which the user can add a list of numbers to take the mean of:
$(function () {
$('button').click(calculate)
})
var number1 = $('#number1').val()
var number2 = $('#number2').val()
var number3 = $('#number3').val()
var numberOfNumbers = $('input').attr('class').length
function calculate() {
let numbers = $('#numbers').val().split(/[ ,]+/);
let sum = numbers.reduce((c, v) => c + parseInt(v), 0);
let result = sum / numbers.length;
$('span').html(result);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Enter a list of numbers separated by space or comma:</p>
<input type="text" id="numbers" class="numbers">
<button>Calculate</button>
<p>The mean is <span></span></p>
You can use $('input').each() for get inputs in the page and $(e).val() to get value of each element withing the each()
DEMO
$(function() {
$('button').click(calculate)
})
function calculate() {
let result = 0
$('input').each((i, e) => {
let val = parseInt($(e).val());
if (!isNaN(val)) {
result += val
}
})
$('span').html(result / $('input').length);
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<p>Number 1</p>
<input type="text" id="number1" class="numbers">
<p>Number 2</p>
<input type="text" id="number2" class="numbers">
<p>Number 3</p>
<input type="text" id="number3" class="numbers">
<button>Calculate</button>
<p>The mean is <span></span></p>
Best case;
You can use "numbers" class for find it.
var numberOfNumbers = $.find('.numbers').length;
Worst case;
If you think you will use "number" class for something else, you can add an data attribute for numbers such as;
<input type="text" id="number1" class="numbers" data-bla-bla="numbers">
and find specified data attribute;
var numberOfNumbers = 0;
$.each($.find('.numbers'),function(a,b) { if ($(b).attr('data-bla-bla') != undefined && $(b).attr('data-bla-bla') == 'numbers') { numberOfNumbers++; } });
I think what you want is something dynamic like this :)
var count = 1,
total = 0,
mean = 0;
$(document).on('click', '#addNewField', function() {
var containerDiv = document.createElement('div');
containerDiv.className += "inputWrapper";
var inputField = document.createElement('input');
inputField.setAttribute('type', 'number');
inputField.className += 'number';
containerDiv.append(inputField);
var deleteSpan = document.createElement('span');
deleteSpan.className += 'delete';
inputField.after(deleteSpan);
$('#fields').append(containerDiv);
inputField.focus();
count++;
$('#count').text(count);
});
$(document).on('keyup', '.number', function() {
calculate();
});
function calculate() {
total = 0;
mean = 0;
$('.number').each(function() {
total += parseFloat($(this).val());
mean = total / count;
});
$('#total').text(total);
$('#mean').text(mean);
}
$(document).on('click', '.delete', function() {
$(this).parent().remove();
count--;
$('#count').text(count);
calculate();
});
.inputWrapper {
position: relative;
}
.number {
width: 200px;
height: 30px;
line-height: 30px;
font-size: 24px;
padding-left: 30px;
margin: 5px 0;
display: block;
}
table td {
text-align: center;
}
input.number+*:after {
content: "×";
font-size: 32px;
top: 0;
left: 5px;
position: absolute;
}
#addNewField {
height: 30px;
width: 235px;
margin: 10px 0 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<div id="fields">
<div class="inputWrapper">
<input type="number" class="number"><span class='delete'></span>
</div>
</div>
<button id="addNewField">+ Add New Field</button>
<table border="1px" cellPadding="10px">
<tr>
<th>Count</th>
<th>Total</th>
<th>Mean</th>
</tr>
<tr>
<td id="count">1</td>
<td id="total">0</td>
<td id="mean">0</td>
</tr>
</table>

Simple Javascript Loop Using input box variable

I'm just trying to start with JavaScript and have put this little loop together. Providing I put 1 in the start box.. it works fine. If I put anything else though the loop itself never takes place.
According to the console my variables should all match the criteria for the loop to activate so I don't see the problem
function myFunction() {
console.clear();
var Start = document.getElementById("Start").value
console.log("Start=", Start)
var End = document.getElementById("End").value
console.log("End=", End)
var which_one = document.getElementById("which_one").value
console.log("which_one=", which_one)
var i = Start;
console.log("i=", i);
var Counter_Array = "";
console.log("Counter Array =", Counter_Array);
var Counter_Array_Split = "";
console.log("Counter Array Split = ", Counter_Array_Split)
var Show_Me = "";
console.log("Show Me = ", Show_Me)
console.log("------Loop Starts------")
for (; Start < End; Start++) {
console.log("Start=", Start)
console.log("i looped=", Start);
Counter_Array += "," + Start
var Counter_Array_Split = Counter_Array.split(',');
console.log("CounterArrayLog=", Counter_Array);
console.log("Counter Array Split = ", Counter_Array_Split);
// sets all elements with the id demo to have the value of the newURL variable
document.getElementById("array").innerHTML = Counter_Array_Split;
}
console.log("------Loop Ends------")
var Show_Me = Counter_Array_Split[which_one]
console.log("Show Me = ", Show_Me)
document.getElementById("my_val").innerHTML = Show_Me;
}
.My_Form {
display: block;
background-color: orange;
;
border: 1;
width: 500px;
border-style: solid;
border-radius: 5px;
}
.my_div {
display: block;
background-color: lightblue;
;
border: 1;
width: 500px;
border-style: solid;
border-radius: 5px;
}
<h2>Example Javascript Loop</h2>
<div class="My_Form">
Start #: <input type="text" name="Start" id="Start" value="2"><br> End #: <input type="text" name="fname" id="End" value="10"> <br> Show
me the <input type="text" name="fname" id="which_one" value="5">th value in the array <br>
</div>
<br>
<div class="my_div">
The array built was
<p id="array"></p>
The Value picked was
<p id="my_val"></p>
</div><br>
<button onclick="myFunction()">
Click Me
</button>
<br>
You need to use integers in the for loop, by default you use string, so you need to parse it first.
1st problem: '5' < '10' this is false.
2nd problem: '5'++ will convert it to 5 and only after that will be incremented.
function myFunction() {
console.clear();
var Start = parseInt( document.getElementById("Start").value, 10)
console.log("Start=", Start)
var End = parseInt(document.getElementById("End").value, 10)
console.log("End=", End)
var which_one = document.getElementById("which_one").value
console.log("which_one=", which_one)
var i = Start;
console.log("i=", i);
var Counter_Array = "";
console.log("Counter Array =", Counter_Array);
var Counter_Array_Split = "";
console.log("Counter Array Split = ", Counter_Array_Split)
var Show_Me = "";
console.log("Show Me = ", Show_Me)
console.log("------Loop Starts------")
for (; Start < End; Start++) {
console.log("Start=", Start)
console.log("i looped=", Start);
Counter_Array += "," + Start
var Counter_Array_Split = Counter_Array.split(',');
console.log("CounterArrayLog=", Counter_Array);
console.log("Counter Array Split = ", Counter_Array_Split);
// sets all elements with the id demo to have the value of the newURL variable
document.getElementById("array").innerHTML = Counter_Array_Split;
}
console.log("------Loop Ends------")
var Show_Me = Counter_Array_Split[which_one]
console.log("Show Me = ", Show_Me)
document.getElementById("my_val").innerHTML = Show_Me;
}
.My_Form {
display: block;
background-color: orange;
;
border: 1;
width: 500px;
border-style: solid;
border-radius: 5px;
}
.my_div {
display: block;
background-color: lightblue;
;
border: 1;
width: 500px;
border-style: solid;
border-radius: 5px;
}
<h2>Example Javascript Loop</h2>
<div class="My_Form">
Start #: <input type="text" name="Start" id="Start" value="2"><br> End #: <input type="text" name="fname" id="End" value="10"> <br> Show
me the <input type="text" name="fname" id="which_one" value="5">th value in the array <br>
</div>
<br>
<div class="my_div">
The array built was
<p id="array"></p>
The Value picked was
<p id="my_val"></p>
</div><br>
<button onclick="myFunction()">
Click Me
</button>
<br>

Creating a table using JavaScript

I am new to front-end web development and right now I am working on a test task to create a table using javascript.Here is my html file:
<title>Pixel Art Maker!</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Monoton">
<link rel="stylesheet" href="styles.css"> </head> <body>
<h1>Lab: Pixel Art Maker</h1>
<h2>Choose Grid Size</h2>
<form id="sizePicker">
Grid Height:
<input type="number" id="inputHeight" name="height" min="1" value="1">
Grid Width:
<input type="number" id="inputWeight" name="width" min="1" value="1">
<input type="submit" onclick="makeGrid()">
</form>
<h2>Pick A Color</h2>
<input type="color" id="colorPicker">
<h2>Design Canvas</h2>
<table id="pixelCanvas"></table>
<script src="designs.js"></script> </body> </html>
And my javascript file:
function makeGrid() {
var rows=inputHeight; var cols=inputWeight; //Referencw for the body var body=document.getElementsbyTagName("body")[0];
//create a table element and a <tbody> element var table1=document.createElement("table"); var tableBody=document.createElement("tbody");
//creating cells for (var i=0;i<rows;i++){ //creating a table row var R=document.createElement("tr"); for(var j=0;j<cols;j++){ //create a table data element var C=document.createElement("td"); R.appendchild(C);
} //adding the row to the end of the table body
tableBody.appendChild(R); } //putting the <tbody> in the <table> table1.appendChild(tableBody); //appending <table> into <body> body.appendChild(table1);
}
I am supposed to get user input of rows and columns via submit button and generate a table according to that specification.So far my attmepts are unsuccessful,more precisely when I hit submit,nothing happens and the values revert back to "1".
I would really appreciate your guidance and feedback.
You don't need a <form>. There's nothing to submit to.
Use document.getElementById
You already have a <table id> in HTML. Reference it!
You don't need therefore a document.body reference.
To retrieve the integer use parseInt( number, radix ) since input value is a String
Clear your table from existing content before appending new stuff.
Use addEventListener(EventName, callback) instead of inline JavaScript (onclick)
Weight is not Width!
function makeGrid() {
var ELTable = document.getElementById("pixelCanvas"); // You already have it!
var ELInputHeight = document.getElementById("inputHeight");
var ELInputWidth = document.getElementById("inputWidth");
var rows = parseInt(ELInputHeight.value, 10);
var cols = parseInt(ELInputWidth.value, 10); // Weight? you mean Width!
ELTable.innerHTML = ""; // Empty table before inserting new stuff
var tbody = document.createElement("tbody");
for (var i = 0; i < rows; i++) { // N rows...
var R = document.createElement("tr"); // Make row.
for (var j = 0; j < cols; j++) { // N cells...
var C = document.createElement("td"); // Make cell.
R.appendChild(C); // Insert cell into row.
}
tbody.appendChild(R); // Insert row into tbody
}
ELTable.appendChild(tbody); // Insert tbody into table
}
document.getElementById("makeGrid").addEventListener("click", makeGrid);
td { padding:10px; background:#000; }
Height: <input type="number" id="inputHeight" min="1" value="1">
Width: <input type="number" id="inputWidth" min="1" value="1">
<button id="makeGrid">MAKE</button>
<br>
Color: <input type="color" id="colorPicker">
<table id="pixelCanvas"></table>
I create function for generate body of table, and listener for butto
function createTableBody(height, width) {
let tr = document.createElement('tr');
let td = document.createElement('td');
let docFr = new DocumentFragment();
for (let i = 0; i < width; i++) {
tr.append(td.cloneNode());
}
for (let i = 0; i < height; i++) {
docFr.append(tr.cloneNode(true));
}
return docFr;
}
let table = document.getElementById('pixelCanvas');
let createTableButton = document.getElementById('createTableButton');
let inputHeight = document.getElementById('inputHeight');
let inputWidth = document.getElementById('inputWeight');
createTableButton.addEventListener('click', () => {
let parentTable = table.parentNode;
let tableClone = table.cloneNode();
parentTable.replaceChild(tableClone, table);//clear old table
table = tableClone;
tableClone.append(createTableBody(inputHeight.value, inputWidth.value));
// if you need , you can add ajax request
console.log(table)
});
<title>Pixel Art Maker!</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Monoton">
<link rel="stylesheet" href="styles.css"> </head> <body>
<h1>Lab: Pixel Art Maker</h1>
<h2>Choose Grid Size</h2>
Grid Height:
<input type="number" id="inputHeight" name="height" min="1" value="1">
Grid Width:
<input type="number" id="inputWeight" name="width" min="1" value="1">
<input type="button" id="createTableButton">
<h2>Pick A Color</h2>
<input type="color" id="colorPicker">
<h2>Design Canvas</h2>
<table id="pixelCanvas"></table>
</body> </html>
If you need send data to server, you can use ajax, and i replace your submit to button, remove form.
Try this:
<form id="form-grid" method="post" onsubmit="makeGrid()">
<h2 id="grid-size">Choose Grid Size</h2>
<label for="inputHeight">Grid height:</label>
<input type="number" id="inputHeight" name="height" min="1" value="1" aria-describedby="grid-size" />
<label for="inputWeight">Grid width:</label>
<input type="number" id="inputWeight" name="width" min="1" value="1" aria-describedby="grid-size" />
<h2>Pick a color</h2>
<label for="colorPicker">Color:</label>
<input type="color" id="colorPicker" name="color" />
<input type="submit" value="Make Grid" />
</form>
<div id="pixelCanvas"></div>
Do note the addition of explicit label's here. These are important for accessibility!
I've added a submit handler to the form, and removed it from the button. I find it's a bit cleaner, but your approach would ultimately work too.
Then in your designs.js file, you might have:
function makeGrid(event) {
event.preventDefault(); // prevents the form from submitting
var form = document.querySelector('#form-grid');
var rows = form.querySelector('#inputHeight').value;
var cols = form.querySelector('#inputWeight').value;
var wrapper = document.querySelector('#pixelCanvas');
var table = document.createElement('table');
for (var r = 0; r < rows; r++) {
var tr = table.insertRow();
for (var c = 0; c < cols; c++) {
var td = tr.insertCell();
}
}
wrapper.appendChild(table);
}
A few reminders:
Use label to associate a form field with it's visible label. This is necessary for assistive technology such as screen readers.
Consider a fieldset to group all of the options, increasing its accessibility.
Good luck!
As #Katamari said, it looks like you're not properly accessing the elements and getting their values.
To access an element, you can use document.querySelector and pass in a CSS selector.
var rowInput = document.querySelector("#inputHeight");
var colInput = document.querySelector("#inputWidth");
Since you have assigned IDs, you could use document.getElementById
var rowInput = document.getElementById("inputHeight");
var colInput = document.getElementById("inputWidth");
Either way, you'll get an element or null if the element can't be found. Once you have the element, just get the value property to get the user results.
var rows = rowInput.value;
var cols = colInput.value;
If you want to avoid error that could be caused by not finding the element, you can check for the element before referencing the value.
var rows = 1;
var cols = 1;
if (rowInput) {
rows = rowInput.value;
}
if (colInput) {
cols = colInput.value;
}
This can be converted into a single line using a tenary operator
var rows = rowInput
? rowInput.value
: 1;
var cols = colInput
? colInput.value
: 1;

JavaScript Scope - populating text box with multiple selections

I'm sorry for asking a question that I'm sure is simple but I'm stuck. I have a project that requires the user to select 3 notes, the value for each should populate in the text box until the 3rd is entered. After that a compare is done to an array and a notification sent to the user letting them know if they have made a valid selection or not.
The problem I'm having is getting all 3 to populate, each time I click a button it overwrites the existing value. I've tried to push them to an array but it only contains the current value, I've tried a loop but that populates the selection 3x. I'm sure I'm overlooking something simple but have not been able to figure out what it is. Can someone point me in the right direction?
Thanks!
<!doctype html>
<html>
<head>
<title> Scope </title>
<meta charset="utf-8">
<style>
html {
height: 100%;
}
body {
height: 100%;
margin: 0px;
font-family: Helvetica, sans-serif;
}
div#container {
margin: auto;
width: 300px;
}
form {
margin-top: 20%;
}
form input[type="text"] {
font-size: 120%;
text-align: center;
}
form input[type="button"] {
background-color: lightblue;
font-size: 110%;
}
</style>
<script>
function addNote(event) {
var validChords = {
C: "CEG",
F: "FAC",
G: "GBD"
};
var note = event.target.value;
console.log(note);
var getNotes = [];
var noteDisplay = document.getElementById("notesDisplay");
var displayMessage = document.getElementById("message");
getNotes.push(note);
console.log(getNotes);
noteDisplay.value = getNotes;
noteDisplay.innterHTML = getNotes;
displayMessage.innterHTML = "Please Enter Antoher Note!";
//Code below is different things I've been playing with trying to
// figure this out.
// var success = false;
// if (notes.length > 0) {
// if (note) {
// for (var i =0; i < 3; i++) {
// if(notes[i] == note) {
// var found = true;
// getNotes.push(note);
// }
// }
// }
// }
// if (getNotes.length < 3) {
// }
}
window.onload = function() {
var notes = ["C", "D", "E", "F", "G", "A", "B"];
var cButton = document.getElementById("c");
cButton.onclick = addNote;
var dButton = document.getElementById("d");
dButton.onclick = addNote;
var eButton = document.getElementById("e");
eButton.onclick = addNote;
var fButton = document.getElementById("f");
fButton.onclick = addNote;
var gButton = document.getElementById("g");
gButton.onclick = addNote;
var aButton = document.getElementById("a");
aButton.onclick = addNote;
var bButton = document.getElementById("b");
bButton.onclick = addNote;
// your code here
}
</script>
</head>
<body>
<div id="container">
<form>
<p id="message">Enter a major triad chord:</p>
<p>
<input id="notesDisplay" type="text" size="21">
</p>
<p>
<input id="c" type="button" value="C">
<input id="d" type="button" value="D">
<input id="e" type="button" value="E">
<input id="f" type="button" value="F">
<input id="g" type="button" value="G">
<input id="a" type="button" value="A">
<input id="b" type="button" value="B">
</p>
</form>
</div>
</body>
</html>
I finally figured out how to get the entries and compare to the object containing specific values and return either a note or a message to try again. I'm almost there but am having an issue with my loops (I think). When a button is clicked a message is supposed to display saying "please enter another note" until the 3rd selection is made, when the first button is clicked I'm getting the "you have made an invalid selection message" and I don't understand why. The last piece I'm missing is the form is supposed to clear after either message is displayed. This is driving me nuts, can someone give me a hint as to what I still have wrong? Thanks!
Revised Code:
Scope
html {
height: 100%;
}
body {
height: 100%;
margin: 0px;
font-family: Helvetica, sans-serif;
}
div#container {
margin: auto;
width: 300px;
}
form {
margin-top: 20%;
}
form input[type="text"] {
font-size: 120%;
text-align: center;
}
form input[type="button"] {
background-color: lightblue;
font-size: 110%;
}
//Array to hold notes entered by user, counter to hold number of
//buttons clicked
var getNotes = [];
var counter = 0;
//addNote function, collects the notes entered by the user and displays
//them in the text box. When the number of notes entered equals 3 a
//compare is done to the validChords object. If the notes equal a valid
//chord a messages is displayed to the user telling them which chord was
//entered, if the chord is not correct a message is displayed telling
//them to try again. After either the form should be cleared.
function addNote(event) {
var validChords = {
C: "CEG",
F: "FAC",
G: "GBD"
};
var note = event.target.value;
var noteDisplay = document.getElementById("notesDisplay");
var displayMessage = document.getElementById("message");
if (counter <= 3) {
getNotes.push(note);
var removeComma = "";
for (i = getNotes.length-1; i >=0; i--) {
removeComma = getNotes[i]+removeComma;
}
noteDisplay.value = removeComma;
noteDisplay.innerHTML = removeComma;
displayMessage.innerHTML = "Please Enter Antoher Note!";
counter = counter+1;
}
if (counter == 3) {
for (var prop in validChords) {
if (removeComma === validChords[prop]) {
displayMessage.innerHTML = "You have entered a " + prop + "
Chord!";
notesDisplay.innterHTML = " ";
counter = 0;
}
}
} else {
displayMessage.innerHTML = "You have not entered a valid chord,
please try again!";
notesDisplay.innterHTML = " ";
counter = 0;
}
}
window.onload = function() {
var notes = ["C", "D", "E", "F", "G", "A", "B"];
var cButton = document.getElementById("c");
cButton.onclick = addNote;
var dButton = document.getElementById("d");
dButton.onclick = addNote;
var eButton = document.getElementById("e");
eButton.onclick = addNote;
var fButton = document.getElementById("f");
fButton.onclick = addNote;
var gButton = document.getElementById("g");
gButton.onclick = addNote;
var aButton = document.getElementById("a");
aButton.onclick = addNote;
var bButton = document.getElementById("b");
bButton.onclick = addNote;
}
</script>
</head>
<body>
<div id="container">
<form>
<p id="message">Enter a major triad chord:</p>
<p>
<input id="notesDisplay" type="text" size="21">
</p>
<p>
<input id="c" type="button" value="C">
<input id="d" type="button" value="D">
<input id="e" type="button" value="E">
<input id="f" type="button" value="F">
<input id="g" type="button" value="G">
<input id="a" type="button" value="A">
<input id="b" type="button" value="B">
</p>
</form>
</div>
</body>
</html>
I believe it's because you initialize getNote to an empty array every time you call the addNote function, check if that is the problem.
Thanks

Dynamic Javascript Div

Got JS Fiddle to work
http://jsfiddle.net/pskjxofo/
Attached I have the following function, the purpose of which is to perform basic calculation. I also added a feature for adding more boxes for calculation. What I am currently stuck on is how to tell Javascript to make dynamic divs, and how to tell it to perform the same calculations for each line every time I click on Calculate. Assistance on this would be greatly appreciated. Thank you all in advance.
<div id="redo">
2 X
<input type="text" id="initial">
= <input type="text" id="solved">
<input type="submit" value="Calculate" onclick="calculait()">
<input type="submit" value="Add Another Box" onclick="addmore()">
</div>
<div id="main"></div>
<script type="text/javascript">
function calculait(){
var first = document.getElementById('initial');
var second = document.getElementById('solved');
second.value = first.value * 2;
}
function addmore(){
var bar = document.getElementById('main');
bar.innerHTML = bar.innerHTML + "<div id='redo'>2 X
<input type='text' id='initial'> = <input type='text' id='solved'>
<input type='submit' value='Calculate' onclick='calculait()'
<input type='submit' value='Add Another Box' onclick='addmore()";
}
</script>
Here is one of the many ways to do it. You could have this HTML structure:
<div id="main">
<div class="operation">
2 X <input type="text" class="initial"/>=
<input type="text" class="solved"/>
</div>
</div>
<input type="submit" value="Calculate" onclick="calculait()"/>
<input type="submit" value="Add Another Box" onclick="addmore()"/>
And this JS:
// Main container for all operations
var main = document.getElementById('main');
// Piece of HTML you'll be duplicating
var op = document.getElementsByClassName('operation')[0].outerHTML;
function calculait() {
// Get every operation div
var operations = document.getElementsByClassName('operation');
// For each of them, calculate
for(var i=0, l=operations.length; i<l; i++){
operations[i].getElementsByClassName('solved')[0].value =
parseFloat(operations[i].getElementsByClassName('initial')[0].value) * 2;
}
}
function addmore() {
main.insertAdjacentHTML('beforeend',op);
}
JS Fiddle Demo
If I understood correctly, I think this code will help.
First of all, change your ids for classes (IDs must be always unique in the page).
<input type="text" class="initial">
<input type="text" class="solved">
And in the JS, you use a for to iterate for this elements.
function calculait() {
var initial = document.getElementsByClassName('initial');
var solved = document.getElementsByClassName('solved');
for (var i = 0; i < initial.length; i++) {
solved[i].value = initial[i].value * 2;
}
}
function addmore() {
var bar = document.getElementById('main');
var html = "<div>2 X ";
html += "<input type='text' class='initial'> = ";
html += "<input type='text' class='solved'>";
html += "</div>";
bar.innerHTML = bar.innerHTML + html;
}
JSFiddle: http://jsfiddle.net/pskjxofo/2/
Give it a try and let me know if it helps!
When you write JavaScript use a debugger, your code didn't parse. You can find one in your browser by hitting F12.
Don't repeat yourself. A clean solution is to put html to duplicate into a template or similar and call a function to copy it.
Use input type=number for numbers.
<html>
<meta charset="utf-8">
<template id="calculate_template">
<form id="" class="calculate_form">
<input value="2" type="number" name="initial_1"> X
<input type="number" name="initial_2"> =
<input type="number" name="solved" disabled="disabled" >
</form>
</template>
<div id="main">
<button onclick="addmore();">Add Another Box</button>
<button onclick="calculate();">Calculate</button>
</div>
<script type="text/javascript">
function calculate(){
/*Calculates all*/
var forms = document.getElementsByClassName('calculate_form'),
i,
length = forms.length;
for(i = 0; i < length; i++){
console.log(forms[i]);
forms[i]['solved'].value = forms[i]['initial_1'].value * forms[i]['initial_2'].value;
}
}
function addmore(){
var main = document.getElementById('main');
main.insertAdjacentHTML("beforeend", document.getElementById('calculate_template').innerHTML);
}
addmore();
</script>
</html>
Demonstration
Here's a way of doing it:
var counter = 0;
function calculait(calculationId) {
var first = document.getElementById('initial' + calculationId);
var second = document.getElementById('solved' + calculationId);
second.value = first.value * 2;
}
function addmore() {
counter++;
var bar = document.getElementById('main');
var newDiv = document.createElement("div");
newDiv.id = "redo" + counter;
newDiv.innerHTML = "2 X <input type='text' id='initial" + counter + "'/> = <input type='text' id='solved" + counter + "'/><input type='submit' value='Calculate' onclick='calculait(" + counter + ")'/><input type='submit' value='Add Another Box' onclick='addmore(" + counter + ")'/>";
bar.appendChild(newDiv);
}
<div id="main"><div id="redo0">2 X <input type="text" id="initial0" /> = <input type="text" id="solved0" /><input type="button" value="Calculate" onclick="calculait(0)" /><input type="button" value="Add Another Box" onclick="addmore(0)" /></div>
</div>
HTML
<p id="operations"></p>
<p>
<input type="submit" value="Calculate" onclick="calc()" />
<input type="submit" value="Add operation" onclick="addOp()" />
</p>
Javascript
var id = 0, multiplier = 2;
var operations = document.getElementById('operations');
function addOp() {
++id;
var p = document.createElement("p");
var right = document.createElement("input");
right.id = 'right_' + id;
right.type = 'text';
var result = document.createElement('input');
result.id = 'result_' + id;
right.type = 'text';
p.innerHTML = multiplier + ' x ';
p.appendChild(right);
p.innerHTML += ' = ';
p.appendChild(result);
operations.appendChild(p);
}
function calc() {
for(var i = 1; i <= id; i++) {
var right = document.getElementById('right_' + i);
var result = document.getElementById('result_' + i);
result.value = multiplier * right.value;
}
}
addOp();
JSFiddle : http://jsfiddle.net/0Lcg0pyz/

Categories

Resources