Display script variables in table td - javascript

I want to display a calculated value in a table without using input..
Here is my script....
<script type="text/javascript">
function totalIt() {
var input = document.getElementsByName("product");
var total = 0;
for (var i = 0; i < input.length; i++) {
if (input[i].checked) {
total += parseFloat(input[i].value);
}
}
document.getElementsByName("total")[0].value = total.toFixed(0);
}
</script>
and my html is....
echo "<td align='right' data-label='Option Prices'> **DISPLAY THE VALUE HERE** </td>";

If I am reading your question correctly you can use the following (i.e., you want to display the calculated value without using an input field):
document.querySelector('[data-label="Option Prices"]').innerText = total.toFixed(0);

If you want to format your answer like "15,900" which is a US English locale standard use the following
document.querySelector('[data-label="Option Prices"]').innerText = new Intl.NumberFormat().format(total.toFixed(0))
More types of formatting and documentation here

Related

Is there an error in my code or have I simply written it wrong?

I'm making a code where if you press the button after the name it will move to the other list. Pressing a button give me the error: "missing ) after argument list". I can't seem to find anything wrong in the code.
<!DOCTYPE html>
<html>
<title>Favoritter</title>
<body>
<p>Hotell</p>
<p id="hotellDiv"></p>
<p>Favoritter</p>
<p id="favDiv"></p>
</body>
<script>
let hotelliste = ["Norwegian Wild", "Stofjord Hotel", "Norefjell Ski og Spa", "Brikdalsbre Fjellstove", "Gudvangen Fjordtell"];
let favoritter = [];
skrivhliste();
skrivfliste();
function skrivhliste(){
document.getElementById("hotellDiv").innerHTML = "";
for (var j = 0; j < hotelliste.length; j++){
document.getElementById("hotellDiv").innerHTML += hotelliste[j] + "<input type=\"button\" onclick=\"leggTil("+hotelliste[j]+")\"><br>";
}
}
function skrivfliste(){
document.getElementById("favDiv").innerHTML = "";
for (var j = 0; j < favoritter.length; j++){
document.getElementById("favDiv").innerHTML += favoritter[j] + "<input type=\"button\" onclick=\"fjern("+favoritter[j]+")\"><br>";
}
}
function leggTil(hotell){
if (hotelliste.indexOf(hotell) > -1) {
hotelliste.splice(hotelliste.indexOf(hotell), 1);
}
favoritter.push(hotell);
skrivhliste();
}
function fjern(hotell){
if (favoritter.indexOf(hotell) > -1) {
favoritter.splice(favoritter.indexOf(hotell), 1);
}
hotelliste.push(hotell);
skrivfliste();
}
</script>
</html>
Look at this:
"<input type=\"button\" onclick=\"fjern("+favoritter[j]+")\">
What string are you going to end up with when you insert the value of favoritter[j]?
<input type="button" onclick="fjern(Norwegian Wild)">
There you don't have the string "Norwegian Wild", you have the variable Norwegian followed by a space followed by the variable Wild (and neither of those variables exist).
If you are programatically generating JavaScript then you need to generate the quotes that go around strings you generate.
This is hard to do well. Especially when that JS gets embedded in HTML that you are also generating on the fly. You have multiple levels of escape sequences to deal with.
Avoid generating strings like this. Use direct DOM methods instead.
For example:
Once, so it can be reused:
function clickHandler(event) {
const button = event.currentTarget;
const hotel = button.dataset.hotel;
leggTil(hotel);
}
Then inside your loop:
const button = document.createElement('input');
button.type = 'button';
button.value = 'display label';
button.dataset.hotel = hotelliste[j];
button.addEventListener('click', clickHandler);
document.getElementById("hotellDiv").appendChild(button);
Your code is ok, please make a string into onclick function like below.
Pass the value in single quotes into both onclick function.
document.getElementById("favDiv").innerHTML += favoritter[j] + "<input type=\"button\" onclick=\"fjern('"+favoritter[j]+"')\"><br>";

Reading text in columns from HTML tables

I've been debugging for some time, trying to get the value of a column in a table. I think once I've done this, it should be easy to pass the value in the next column out of my JS function.
My HTML table is:
<table id="country_LE_table" style = "display:none">
<tr>
<td>Japan</td>
<td>83.7</td>
</tr>
<tr>
<td>Switzerland</td>
<td>83.4</td>
</tr>
</table>
My Javascript is:
<script type="text/javascript">
function getLifeExpectancy() {
var Country = "<?php echo $Country ?>";
document.write(Country); // this gets read OK
var table = document.getElementById("country_LE_table");
var tr = table.getElementsByTagName("tr");
document.write(tr.length); document.write("<br>"); // works as expected
for (var i = 0; i < tr.length; i++) {
document.write(tr[i].innerHTML); document.write("<br>"); // works well up to here
// the following doesn't work
var td = tr[i].getElementsByTagName("td")[0];
if (td = Country) { //need td.fullHTML/value/fullText?
return tr[i].getElementsByTagName("td")[1]; // return the number
}
document.getElementById("demo").innerHTML = getLifeExpectancy();
</script>
If I do document.write(td), I get "[object HTMLTableCellElement]" on my page.
If I do document.write(td.fullHTML) I get "undefined" on my page.
When I explore other methods than td.innerHTML, I get this - it looks like I can't use functions based around text.
Use this instead. you have used assignment operator instead of comparison operator "=="
if (td.innerHTML == Country)
{
}

Issue with getting a keyup function to get sum of input field values using plain Javascript

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>

Javascript - How do you set the value of a button with an element from an array?

<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]);

How to get value from multiple different textbox through javascript

<html>
<head>
<script>
function showUser()
{
for (var i = 0; i < 10; i++)
{
var internal = document.getElementById("inte[i]").value; /* but its not working */
var external = document.getElementById("exte[i]").value;
}
}
</script>
</head>
<body>
<?php
for (i = 0; i < 10; i++)
{
echo "<td><input type='text' name='internal' id = 'inte[$i]' width='30'/> </td>";
echo "<td><input type='text' name='external' id = 'exte[$i]' width='30'/> </td>";
}
echo "<td><input type='submit' name='submit1' value='Save Marks' width='30' onclick = 'showUser()' /></td>";
?>
</body>
<html>
i am using the above code but i cant get 10 values of different textboxes
how to fetch these value through java script and i want to save it to database kindly help me
i am using the above code but i cant get 10 values of different textboxes
how to fetch these value through java script and i want to save it to database kindly help me
You are not placed i value in getElementById
Replace your
document.getElementById("inte[i]").value;
as
document.getElementById("inte["+i+"]").value;
Make your for loop as
for (var i=0; i<10; i++)
{
var internal = document.getElementById("inte["+i+"]").value; /* but its not working */
var external = document.getElementById("exte["+i+"]").value;
}
This isn't doing what you think:
getElementById("inte[i]")
That's just a string, the i value doesn't get interpreted into an integer. This would:
getElementById("inte[" + i + "]")
When your Javascript for loop runs you are are overwriting your var internal and external each time so after the for loop runs you will only have the last value that was assigned to the variables. You should use an array and push the values of the text boxes into it.
var internal = new Array();
var external = new Array();
for (var i=0; i<10; i++)
{
internal.push(document.getElementById("inte["+i+"]").value); /* but its not working */
external.push(document.getElementById("exte["+i+"]").value);
}

Categories