JavaScript Functions & Equations - javascript

I'm trying to complete a simple multiplication problem of an input and a number already there (5.49) using JavaScript and the Compute function. I have it inside of a table and am using internal css for the structure of the page.
My problem is the when I press the compute button on the page, the answer to the equation (input)*5.49 doesn't come up, but instead nothing does. I'm struggling to find mistake.
Additional Notes: I've already checked to see if the compute button was working by replacing the formula with a pop-up box and it was working.
<!DOCTYPE html>
<html>
<head>
<title>Project</title>
<style type="text" /css>
.inbox { width=30px; text-align: right; border: 2px solid black; } .align { text-align: right }
</style>
<script type="text/javascript">
function compute() {
var a = form1.inputA.value;
a = parseFloat(a);
var b = form1.inputB.value;
b = parseFloat(b);
var c = form1.inputC.value;
c = parseFloat(c);
var e = a * 5.49;
form1.sumA.value = e.toFixed(2);
}
function pageInit() {
form1.inputA.focus();
}
</script>
</head>
<body onload="pageInit();">
<form id="form1">
<table border="2">
<tr>
<th colspan="4">Sample Order Form</th>
</tr>
<tr>
<th>Quantity</th>
<th>item</th>
<th>Unit Price</th>
<th>Totals</th>
</tr>
<tr>
<th>
<input tabindex="1" class="inbox" type="text" id="inputA" />
</th>
<th>Apples</th>
<td>$5.49</td>
<th>
<input class="inbox" type="text" id="sumA" readonly="readonly" />
</th>
</tr>
<tr>
<th>
<input tabindex="4" type="button" value="Compute" onclick="compute();" />
</th>
</tr>
</table>
</form>
</body>
</html>

The fields inputB and inputC just don't exist. Then it produce an error.
function compute() {
var a = form1.inputA.value;
a = parseFloat(a);
var e = a * 5.49;
form1.sumA.value = e.toFixed(2);
}
You can use web developer tools to analyze your code.
Modern web browser have tools like that.
Take a look at google chrome developer tools : https://developer.chrome.com/devtools for example. You can find equivalent tools for firefox and Internet Explorer.

Related

I want to show the total rows beside the search and make search code work in python?

I created a table and I want to do a search for two columns (code and name) so when the user enters any letter or number of name, code columns it shows all row names containing that letter
and I want to show the total rows of my table next to search box.
in HTML
<input type="text" class="form-control" onkeyup="searchrecords" id="searchtext" placeholder="Search" aria-label="Text input with dropdown button">
<h6 class="mt-3 mx-4">Total: </h6>
</div>
</div>
<table class="table table-striped " id="table1">
<thead>
<tr class="feed-bg text-white ">
<th>ID</th>
<th>Employee Code</th>
<th>Employee Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{% for i in data_list %}
<tr>
<td>{{ forloop.counter }}</td>
<td>{{i.employee_code}}</td>
<td>{{i.employee_name}}</td>
<td>{{i.email}}</td>
</tr>
{% endfor %}
</tbody>
</table>
In JS I did the search code but it does not work!
function searchrecords()
{
var input,table,tr,td,filter;
input=document.getElementById("searchtext");
filter=input.value.toUpperCase();
table=document.getElementById("table1");
tr=table.getElementsByTagName("tr");
for(i=0;i<tr.length;i++)
{
td=tr[i].getElementsByTagName("td")[0];
if(td)
{
textdata=td.innerText;
if(textdata.toUpperCase().indexOf(filter)>-1)
{
tr[i].style.display="";
}
else
{
tr[i].style.display="none";
}
}
}
}
I made an example for you here. Maybe it helps.
const input = document.getElementById("searchtext");
const rowNum = document.getElementById("row-num");
const table = document.getElementById("table1");
const tr = Array.from(table.getElementsByTagName("tr"));
function renderRowNr() {
rowNum.innerHTML = tr.filter((row) => row.style.display !== "none").length;
}
function resetRows() {
tr.forEach((row) => (row.style.display = "inherit"));
}
function searchrecords() {
resetRows();
input.value &&
tr
.filter((row) => {
return !Array.from(row.children)
.map((cell) => {
return cell.textContent
.toUpperCase()
.includes(input.value.toUpperCase());
})
.some((cell) => cell === true);
})
.forEach((row) => (row.style.display = "none"));
renderRowNr();
}
function init() {
resetRows();
renderRowNr();
input.addEventListener("change", () => searchrecords());
}
init();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<label>Filter: </label>
<input id="searchtext" />
<p>row number: <span id="row-num"></span></p>
<table class="table table-striped" id="table1">
<tbody>
<tr>
<td>1</td>
<td>abc</td>
<td>Lokrum</td>
<td>email1</td>
</tr>
<tr>
<td>2</td>
<td>def</td>
<td>Lara</td>
<td>email2</td>
</tr>
<tr>
<td>3</td>
<td>ghi</td>
<td>Lora</td>
<td>email3</td>
</tr>
</tbody>
</table>
<script src="app.js"></script>
</body>
</html>
It looks as though your code loops through all the rows, then for each row checks the first cell in the row (td[0]) against the input field. It looks as though the first cell in the row contains a counter so presumably will not match the input text?
Try sticking in some console.log statements in your loop to check what is happening (or step through in a debugger)
It would be easier if you shared all of the relevant generated HTML (including 'searchtext' input). Assuming you are happy with the HTML that has been generated, then the final HTML will be more useful rather than the django markup.
You should probably remove the python and django tags from your question as it seems that your issue is purely with HTML/JS

How to enable editing table cell data on multiple rows?

How can I enable data editing inside a table cell with javascript on multiple row.
I have written a code that gets the cell data and replace it with a text box that has previous data on it and saves the data in to the cell after you finished editing. But I want to make it possible with multiple table rows. Btw. the table will be Php generated.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<title>EDIT USER</title>
<script>
function edit() {
var a = document.getElementById("fname").innerHTML;
var b = document.getElementById("lname").innerHTML;
document.getElementById("fname").innerHTML='<input id="fnamefld" type="text" value="'+a+'"'+' />';
document.getElementById("lname").innerHTML='<input id="lnamefld" type="text" value="'+b+'"'+' />';
document.getElementById("edit_btn").disabled=true;
document.getElementById("done_btn").disabled=false;
}
function done() {
document.getElementById("done_btn").disabled=true;
document.getElementById("edit_btn").disabled=false;
var a = document.getElementById("fnamefld").value
var b = document.getElementById("lnamefld").value
document.getElementById("fname").innerHTML=a;
document.getElementById("lname").innerHTML=b;
}
</script>
</head>
<body>
<table border="0">
<th>First Name</th>
<th>Last Name</th>
<th>Edit?/Done?</th>
<tr>
<td id="fname">User fname</td>
<td id="lname">User lname</td>
<td>
<button id="edit_btn" onclick="edit()">Edit!</button>
<button id="done_btn" onclick="done()">Done!</button>
</td>
</tr>
</table>
<script> document.getElementById("done_btn").disabled=true;</script>
</body>
</html>
I have used this plugin in the past and found it incredibly useful
http://vitalets.github.io/x-editable/

Simply Javascript to total up form fields, where's my issue?

The goal is to take the number of orders for each type and calculate the total price for all of them when you click total cost. But I cant seem to get it to work google debugger says
Uncaught SyntaxError: Unexpected token ; 13
Uncaught ReferenceError: compute is not defined
Edit: Fixed the Parenthesis but now i'm having issues with the output lin that returns the total.
Edit2: added .value to return
[SOLVED]
<head>
<title>Coffee Order Form</title>
<script type="text/javascript">
function compute()
{
//input
var french = Number(document.getElementById("french").value;
if(isNaN(french))
{
french=0;
}
var hazelnut = Number(document.getElementById("hazelnut").value);
if(isNaN(hazelnut))
{
hazelnut=0;
}
var columbian = Number(document.getElementById("columbian").value);
if(isNaN(columbian))
{
columbian=0;
}
//calculate
var total = 3.49 * french + 3.95 * hazelnut + 4.59 * columbian;
//output
return document.getElementById("total").value = "$" + total.toFixed(2);
}
</script>
</head>
<body>
<form method="post" action="http://uta.edu">
<table border="2">
<caption><b>Coffee Order Form</b></caption>
<tr>
<th>Product Name</th>
<th>Price</th>
<th>Quantity</th>
</tr>
<tr>
<th>French Vanilla</th>
<th>$3.49</th>
<td><input type="text" id="french"></td>
</tr>
<tr>
<th>Hazelnut Cream</th>
<th>$3.95</th>
<td><input type="text" id="hazelnut"></td>
</tr>
<tr>
<th>Columbian</th>
<th>$4.59</th>
<td><input type="text" id="columbian"></td>
</tr>
</table>
<input type="button" value="Total Cost" onclick="compute()">
<input type="text" id="total">
<br/>
<input type="submit" value="Submit Order">
<input type="reset" value="Clear Order Form">
</form>
</body>
You are missing the ending parentheses for all 3 calls to Number():
var french = Number(document.getElementById("french").value;
Should be:
var french = Number(document.getElementById("french").value);
Because of the syntax error, the function is not available to your code within the Body. Thus, the uncaught reference error.
In multiple places parentheses are not balanced e.g.:
var french = Number(document.getElementById("french").value --->)<---- missing;
The best minimum practice is to put javascript code in .js files, use a tool like pychecker to check syntax of files and then you insert with
<script src=".."></script>
For even better results use jasmine or a similar framework to test your javascript code first.
All your Number functions lack the closing parenthesis:
var french = Number(document.getElementById("french").value);
var hazelnut = Number(document.getElementById("hazelnut").value);
var columbian = Number(document.getElementById("columbian").value);

How can I update a set of text fields on key press and avoid resetting a form on submit?

I'm trying to make a simple converter like this one, but in JavaScript, where you enter an amount in tons and it displays a bunch of different numbers calculated from the input, sort of like this:
This is what I've tried:
<html>
<head>
<title>Calculator</title>
<script type="text/javascript">
function calculate(t){
var j = document.getElementById("output")
var treesSaved = t.tons.value * 17;
j.value = treesSaved;
}
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" />
<input type="button" value="Calculate" onclick="calculate(this.form)" />
<br />
<input type="text" id="output" value="Output" />
</form>
</body>
</html>
This works, to the extent that when you press the button, it calculates and displays the right number. However, it also seems to reset the form when I press the button, and I'm hoping to eliminate the need for the button altogether (so on every key press it recalculates).
Why is the form resetting, and how could I extend this to not need the button at all?
Here is the fiddle link for it:
Calculator
Use the below code to achieve what I think you want to :
<html>
<head>
<title>Calculator</title>
<script type="text/javascript">
function calculate(t){
var j = document.getElementById("output");
var rege = /^[0-9]*$/;
if ( rege.test(t.tons.value) ) {
var treesSaved = t.tons.value * 17;
j.value = treesSaved;
}
else
alert("Error in input");
}
</script>
</head>
<body>
<form>
<input type="text" placeholder="Tons" id="tons" onkeyup="calculate(this.form)"/>
<input type="button" value="Calculate" onclick="calculate(this.form)" />
<br />
<input type="text" id="output" value="Output" />
</form>
</body>
</html>
Please check this FIDDLE.
All you need to adding attributes data-formula to your table cells.
HTML
<table border="1">
<tr>
<td>
<input type="text" id="initial-val" />
</td>
<td>card board</td>
<td>recycled</td>
<td>reusable</td>
</tr>
<tr>
<td>lovely trees</td>
<td data-formula='val*5'></td>
<td data-formula='val+10'></td>
<td data-formula='val/2'></td>
</tr>
<tr>
<td>what is acres</td>
<td data-formula='val*2'></td>
<td data-formula='val*(1+1)'></td>
<td data-formula='val*(10/5)'></td>
</tr>
</table>
JAVASCRIPT
$(function () {
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var $input = $('#initial-val'),
$cells = $('td[data-formula]');
$input.on('keyup', function () {
var val = $input.val();
if (isNumber(val)) {
$.each($cells, function () {
var $thisCell = $(this);
$thisCell.text(
eval($thisCell.attr('data-formula').replace('val', val.toString()))
)
});
} else {
$cells.text('ERROR')
}
});
});
You'll need:
a drop down option that allows the user to select what type of calculation they want to do and then display an input field OR multiple input fields
an input field for user input
a submit button with a onclick() event which passes your input into your calculation
(you may want to do some validation on this so they can only enter numbers)
validation examples
your Javascript file that takes the input from your box on submit and performs your calculation
display the information back to user... something like innerHtml to an element you've selected or:
var output = document.getelementbyid("your outputbox")
output.value = "";
output.value = "your calculated value variable";
Here is a tutorial for grabbing user input.
Assuming your calculations are all linear, I would suggest that you create an array of the coefficients and then just loop that array to do the calculation and print it out. Something like this:
HTML:
<table>
<tr>
<th></th>
<th>Recycled Cardboard</th>
<th>Re-usable Cardboard</th>
</tr>
<tr>
<th>Trees Saved</th>
<td></td><td></td>
</tr>
<tr>
<th>Acres Saved</th>
<td></td><td></td>
</tr>
<tr>
<th>Energy (in KW)</th>
<td></td><td></td>
</tr>
<tr>
<th>Water (in Gallons)</th>
<td></td><td></td>
</tr>
<tr>
<th>Landfill (Cubic Yards)</th>
<td></td><td></td>
</tr>
<tr>
<th>Air Pollution (in Lbs)</th>
<td></td><td></td>
</tr>
</table>
Javascript:
function showStats(cardboardTons) {
var elements = $("td");
var coeffs = [17, 34, 0.025, 0.5, 4100, 8200, 7000, 14000, 3, 6, 60, 120];
for(var i=0;i<coeffs.length;i++)
elemnts.eq(i).html(cardboardTons * coeffs);
}
Once you get input from the user, pass it into the showStats function as a number and it will go through all of the cells in the table and calculate the proper number to go in it.

Load a script for the elements of an array

I am trying to create a dynamic form where you can order something.
In basic form, we have one row, but if you want to order more things we can dynamically without reloading the page, add the new row. So far everything is working properly for me, but in this form we have two dropdown ("input select") lists. These drop-down lists are dependent on each other and do not know how to load them the relationship between them and the option of choice. I have tried many different examples from the internet, but always work correctly only the first default row. Dynamically created rows are no longer dependent on one another.
If I am doing something wrong, and you know a better way, please show me this way.
I ask you for help, because I really depend on that. Thank you in advance. ;)
Update
Hmm .. Now I understand, but I do not know much how to use it in my web page code. Will show you the web page code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><br>
<html><br>
<head><br>
<title>Dynamic forms</title><br>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><br>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script><br>
<script type="text/javascript" src="http://jquery.bassistance.de/validate/jquery.validate.js"></script><br>
<script language="javascript" src="chainedselects.js"></script><br>
<script language="javascript" src="exampleconfig2.js"></script><br>
</head>
<body onload="initListGroup('vehicles', document.formm.elements['group[]'], document.formm.elements['product[]'], 'cs')">
<script type="text/javascript">
$(document).ready(function(){
var i = 2;
var templateRow = jQuery.format($("#template").val());
function addRow() {
var ii = i++;
$(templateRow(ii)).appendTo("#listProducts tbody");
$("#removeProduct_" + ii).click(function(){
$("#row_" + ii).remove();
});
}
$("#addProduct").click(addRow);
});
</script>
<!-- Template row in the table -->
<textarea id="template" style="display:none;" cols="1" rows="1">
<tr id="row_{0}" valign="top">
<td>{0}.</td>
<td><select name="group[]" style="width: 100%;"></select></td>
<td><select name="product[]" style="width: 100%;"></select></td>
<td><input type="text" name="price[]" style="width: 100px;"></td>
<td><input type="text" name="quantity[]" style="width: 97%;"></td>
<td><img src="remove.png" id="removeProduct_{0}" alt="remove"></td>
</tr>
</textarea>
<!-- This summary table -->
<form name="formm" action="parser.php" method="post">
<table id="listProducts" name="list">
<thead>
<tr>
<th>Nr</th>
<th>Group</th>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>+/-</th>
</tr>
</thead>
<tfoot>
<tr>
<th colspan="3" align="left">
<input type="submit" name="send" value="Send" style="width: 100px;">
</th>
</tr>
</tfoot>
<tbody>
<tr valign="top">
<td>1.</td>
<td><select name="group[]" style="width: 100%;"></select></td>
<td><select name="product[]" style="width: 100%;"></select></td>
<td><input type="text" name="price[]" style="width: 100px;"></td>
<td><input type="text" name="quantity[]" style="width: 97%;"></td>
<td><img src="add.png" id="addProduct" alt="add"></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
This is a parser.php:
<?php
$data = array();
$data['Groups'] = $_POST['group'];
$data['Products'] = $_POST['product'];
$data['Prices'] = $_POST['price'];
$data['Quantity'] = $_POST['quantity'];
$result = print_r($data,true);
echo "<pre>$result</pre>";
?>
Here is link to all code.
The click events are not attached to the newly created rows, so you need to make sure that any new rows, after they are created have click events attached to them.
function dependantFunction() {
/* code */
}
function addNewRow() {
var a=document.createElement("div");
var b=document.createElement("img");
b.src="images/add.png";
b.addEventListener("click", dependantFunction, false);
a.appendChild(b);
document.getElementById("rowholder").append(a);
}
Then all new rows should have all the necessary events attached to them.

Categories

Resources