I'm working on a personal project and I've run into an issue that I haven't been able to solve.
Here is a function that generates new table rows into a table (with id of "tableData") when a button is clicked:
function addNewRow(){
var tableEl = document.getElementById("tableData");
var newLine = '<tr class="newEntry">';
var classArray = ["classA", "classB", "classC", "classD"];
for (var i = 0; i < classArray.length; i++){
newLine += '<td><input class="' + classArray[i] + '"></td>';
}
newLine += '</tr>';
tableEl.insertAdjacentHTML("beforeend", newLine);
}
document.getElementById("addRow").addEventListener("click", addNewRow, false);
//the element with id="addRow" is a button
I've simplified the code for the above function for the sake of readability as it's not the focus of the problem. When the button is clicked, a new row is added successfully.
The problematic part involves another function that takes the sum of the respective classes of each row and displays them in a div.
The goal is to get the sum of the values of all input fields with matching class names. For example, let's say I use the addNewRow function to get six rows. Then I want to have the div showing the sum of the values of all input fields with the class name of "classA"; the number in that div should be the sum of those six values, which gets updated as I type in the values or change the existing values in any of the input fields with class name of "ClassA".
function sumValues(divId, inputClass){
var sumVal = document.getElementsByClassName(inputClass);
var addedUp = 0;
for (var j = 0; j < sumVal.length; j++){
addedUp += Number(sumVal[j].value);
}
document.getElementById(divId).innerHTML = addedUp;
}
Here are a couple (out of several) failed attempts:
document.input.addEventListener("keyup", sumValues("genericDivId", "classA"), false);
document.getElementsByClassName("classA").onkeyup = function(){sumValues("genericDivId", "classA");}
Unfortunately, after scouring the web for a solution and failing to find one, I just added an event listener to a button that, when clicked, would update the div to show the sum of values. Also had to modify the sumValues function to take values from an array rather than accepting arguments.
My question is: How can I modify the code so that the sum value updates as I type in new values or change existing values using pure Javascript (vanilla JS)?
You are very close, document.getElementsByClassName() returns an array of DOM objects, you need to set the onkeyup function for each and every element by looping through that array.
var classA = document.getElementsByClassName('classA'); // this is an array
classA.forEach(function(elem){ // loop through the array
elem.onkeyup = function(){ // elem is a single element
sumValues("genericDivId", "classA");
}
}
Hopefully this fixes your issue
Maybe the example below is not same with your situation, but you'll get the logic, easily. Anyway, do not hesitate to ask for more guide.
document.getElementById("row_adder").addEventListener("click", function() {
var t = document.getElementById("my_table");
var r = t.insertRow(-1); // adds rows to bottom - change it to 0 for top
var c = r.insertCell(0);
c.innerHTML = "<input class='not_important_with_that_way' type='number' value='0' onchange='calculate_sum()'></input>";
});
function calculate_sum() {
var sum = ([].slice.call(document.querySelectorAll("[type=number]"))).map(e=>parseFloat(e.value)).reduce((a, b) => a+b);
document.getElementById("sum").innerHTML = sum;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div>
<p>
<strong>Sum</strong>:<span id="sum">0</span>
</p>
</div>
<button id="row_adder">
Click me
</button>
<table id="my_table">
</table>
</body>
</html>
I'm just putting this out there to see if anyone can catch my drift and give a hand..
I work for a public library and am in the process of making a "Self Checkin" machine.
Here's some code from it - There's a form called "checkin" with an input called "barcode" - the result of "barcode" is posted to a php file which the sends the data to the Library System and receives a message which is then passed into a table "completed-checkins".
It's all working fine but - I need to put some conditions on what data is accepted from the form.. The conditions are the first two characters need to be t00 .
I've been searching the web and trying to borrow/adapt code from others to make this work, which is where i got this from;
<script type="text/javascript">
function checkCode() {
var form = document.getElementById('checkin');
var x = form.elements.barcode.value.substring(0, 2);
// var x = this.value.substring(0, 2);
if (x == 't00') document.getElementById('#barcode').style.display = 'none';
}
</script>
I'm no real coder but am wondering if anyone who is can see how I could get this to work? (it doesn't at the moment).
Thanks much for looking,
Jordan.
And here's the html with all the scripts;
<body OnLoad="$('#barcode').focus();" style="padding:40px;">
<center>
<p>
<img src="selfchecklogo.png" />
</p>
<div class="formbarwrapper">
<div class="formbar">
<form method="post" name="checkin" id="checkin" onsubmit="return checkCode()" />
<input name="barcode" id="barcode" placeholder="scan an item..." autocomplete="off" maxlength="9" />
</form>
</div>
</div>
<div class="result">
<table id="completed-checkins">
<tbody>
<tr>
<td id="cell"></td>
</tr>
</tbody>
</table>
</div>
</center>
</body>
<script type="text/javascript">
function checkCode() {
var form = document.getElementById('checkin');
var x = form.elements.barcode.value.substring(0, 2);
// var x = this.value.substring(0, 2);
if (x == 't00') document.getElementById('#barcode').style.display = 'none';
}
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#checkin').submit(function() {
$.post("index.php", {
barcode: $('#barcode').val()
},
function(data) {
var content = '';
content += '<div class="result">';
content += '<tbody>';
content += '<tr>';
content += '<td>' + data + '</td>';
content += '</tr>';
content += '</tbody>';
content += '</div>';
$('#barcode').val('').focus();
$('#completed-checkins tbody').html(content);
});
return false;
});
});
</script>
</html>
Have you tried printing "x" to the console? I think your problem is that this line
var x = form.elements.barcode.value.substring(0, 2);
only selects the first two characters out of the string, and then you compare it to "t00", which is three characters long and thus will always evaluate to false.
Also, you might want to consider using the "===" operator instead of the "==" operator. In this case both would work, but using "===" is a good habit to get in to. "===" works the way you expect it to work, whereas "==" has some little gotchas in Javascript. For instance
0 == '0' //This evaluates to true
0 === '0' //This evaluates to false
Basically, "==" doesn't check for type, and "===" does.
<html>
<body>
<script type="text/javascript">
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
</script>
<table>
<tr>
<td><input type = 'button' value = "key[0][1]" /></td>;
</tr>
</table>
</body>
</html>
This is a small example above, but I'm basically making an onscreen keyboard and I already have the loop which positions the buttons, however in my loop I try to assign the value of each key similarly to the code above, but instead of printing q w e r t y for each key, it prints key[row][col] for each button. How do I get the letters to appear on the button using a similar method to the above?
The below code generates the keyboard kind of layout that you are expecting:
<html>
<head>
<script type="text/javascript">
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
</script>
<body>
<script type="text/javascript">
for(var i = 0; i < key.length; i++)
{
document.write("<div>");
for(var j = 0; j < key[i].length; j++)
{
document.write("<input type='button' value='" + key[i][j] + "'/>");
}
document.write("</div>");
}
</script>
</body>
</html>
The only thing the second and third row should move right a little bit to look like real keyboard. For this we can do padding for the div tags. Hope this helps you.
Something like this?
HTML:
<input id="myInput" type="button" />
JavaScript:
var key = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
var input = document.getElementById('myInput');
input.value = key[0][1];
That's the basic idea. You already have a loop to work with. The javascript should be after the HTML on the page. Your elements need to exist before you can grab them. Not sure if this is your precise confusion, though.
You can use javascript to create the elements, but unless there's a reason to do so, you might as well write HTML. If you're using a javascript function to generate the elements as well as fill their values in, you'll need javascript's document.createElement:
var keysArr = [["q","w","e","r","t","y","u","i","o","p"], ["a","s","d","f","g","h","j","k","l"], ["z","x","c","v","b","n","m"]];
var generateKeys = function(keys) {
for (var i = 0 ; i < keys.length ; i++) {
for (var j = 0 ; j < keys[i].length ; j++) {
var input = document.createElement('input');
input.value = key[i][j];
document.appendChild(input); // or put it wherever you need to.
}
}
}
generateKeys(keysArr);
Wrapping it in a function will also allow you to re-use the code with different keyboard layouts if you wanted to, say, let the user choose a different layout on the fly.
You will need to set them programmatically, rather than in the value attribute.
You will also need to create the tr/td/input elements within your loop programmatically, for example:
http://www.dustindiaz.com/add-and-remove-html-elements-dynamically-with-javascript/
When you create the input tag programmatically, you can set the value attribute using javascript - eg.
newInput.setAttribute("value", key[rowIndex, cellindex]);
I am trying to get my content to display on the same page as my button. But when i enter the values and press display the square i am forming is displayed on a new white webpage.
I ask the user to enter two values (height and width), I also ask for a character to form the border of the square, but i have not been able to do that part yet so i just hard coded a # character in for the border in the meantime
What i would like to know is how to display my square on the same page and not in a seperate page.
I use an external JavaScript file: Here is its code. Its named "SquareScript.js":
function Display()
{
var a = document.getElementById("value1").value;
var b = document.getElementById("value2").value;
var outputText = "";
for (var i = 0; i < a; i++)
{
outputText += "#";
}
outputText +="<br>";
for (var r = 0; r < b; r++)
{
outputText += "#";
for(var p = 0; p < a-2; p++)
{
outputText +="  ";
}
outputText += "#";
outputText +="<br>";
}
for (var i = 0; i < a; i++)
{
outputText += "#";
}
}
Here is my webpages code:
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" type = "text/css" href = "Assignment3.css">
<style>
table {background-color:white;color:black;}
body {background-image: url('squares.png');}
</style>
</head>
<body>
<div class = "heading">
<h1><img src = "Interested.png" width = 100px height = 100px></img>WELCOME TO BUILD A SQUARE</h1>
</div>
<script src = "SquareScript.js">
</script>
<table>
<tr>
<td>
Please Enter value number 1:  <input type = "text" id = "value1">
</td>
</tr>
<tr>
<td>
Please Enter value number 2:  <input type = "text" id = "value2">
</td>
</tr>
<tr>
<td>
Please Enter a character:         <input type = "text" id = "character">
</td>
</tr>
<tr>
<td>
<button onclick = "Display()">Display</button>
</td>
</tr>
<div id="output" style = "background-color:blue;"><script>
document.getElementById("output").innerHTML(outputText);
</script></div>
</table>
</body>
</html>
Any useful tips will be appreciated and please consider the fact that I am still new to web development so my code is obviously very basic. Please let me know if you require anything more of me.
The way document.write() works is that when it's called outside the HTML page, it automatically creates a new document and writes into that (see the documentation). This is what's going on in your case: the function is called outside of the HTML (in SquareScript.js) and so it's making a new document, which is the "new white webpage" you're seeing.
You could solve this problem by calling document.write() from within the HTML page. Or you could forego using document.write() and instead reference an element on the existing page (a more flexible solution). By creating a new element in your HTML where the output of your functions should appear (like <div id="output"></div>), you can use document.getElementById("output") to put your script's output into that element.
You don't need to call this every time you want to add content. Instead, create a new variable to hold your output text as you generate it.
var outputText = "";
Then as you go through your loops, you can add to outputText:
for (var i = 0; i < a; i++) {
outputText += "#";
}
Then after all your loops are complete, you can insert the content into the output div by making the following function call as the last thing in your display() function:
document.getElementById("output").innerHTML(outputText);
Do not use document.write. Create <div id="result"></div> on your page and place your output there. You should create a string variable containing your HTML output. Then you can display this HTML using the following code:
document.getElementById("result").innerHTML = my_html_output;
I am new in Javascripting language.
I tried to build an application in which , there is one HTML page from which I get single input entry by using Submit button, and stores in the container(data structure) and dynamically show that list i.e., list of strings, on the same page
means whenever I click submit button, that entry will automatically
append on the existing list on the same page.
HTML FILE :-
<html>
<head>
<script type = "text/javascript" src = "operation_q_2.js"></script>
</head>
<body>
Enter String : <input type= "text" name = "name" id = "name_id"/>
<button type="button" onClick = "addString(this.input)">Submit</button>
</body>
</html>
JAVASCRIPT CODE
var input = [];
function addString(x) {
var s = document.getElementById("name_id").value;//x.name.value;
input.push(input);
var size = input.length;
//alert(size);
printArray(size);
}
function printArray(size){
var div = document.createElement('div');
for (var i = 0 ; i < size; ++i) {
div.innerHTML += input[i] + "<br />";
}
document.body.appendChild(div);
//alert(size);
}
Here it stores the strings in the input Array, but unable to show on the web page. Need help please.
Tell me one more thing there is one code on given link. It also not gives desired answer. Please help me overcome from this problem.
<html>
<body>
<script>
function addValue(a) {
var element1 = document.createElement('tr');
var element2 = document.createElement('td');
var text = document.createTextNode(a);
var table = document.getElementById('t');
element2.appendChild(text);
element1.appendChild(element2);
table.tBodies(0).appendChild(element1);
}
</script>
Name: <input type="text" name="a">
<input type="button" value="Add" onClick='javascript:addValue(a.value)'>
<table id="t" border="1">
<tr><th>Employee Name</th></tr>
</table>
</body>
</html>
In your code where you push an item to the end of your input array, you're trying to push the array instead of the value to the array. So if your problem is that your values aren't being appended to the page is because you're trying to append the array that's empty initially onto itself.
So instead of
input.push(input);
It should be
input.push(s);
Since "s" you already declared to be the value from the text field.
And if you're not going to use that parameter you're passing in, I would get rid of it.
References: Javascript Array.Push()