I'm new to HTML and Javascript, I managed to create the table and slider how I want them. However I'd like the script to be universal, so it can be used on other tables with different values and with more or less rows. I assume that means it will have to create an array from the number of rows and their values?
Any help would be greatly appreciated!
<html>
<body onload="myFunction()">
<table>
<tr>
<td>value one</td>
<td id="value1">0.5</td>
</tr>
<tr>
<td>value two</td>
<td id="value2">5</td>
</tr>
<tr>
<td>value three</td>
<td id="value3">2</td>
</tr>
</table>
<form id="myForm">
<input type="range" id="myRange" defaultvalue="1" value="1" min="0.1" max="2" step="0.1" onclick="myFunction()">
<input type="button" onclick="myReset();myFunction()" value="Reset">
</form>
<script>
function myReset() {
document.getElementById("myForm").reset();
}
function myFunction() {
var x = document.getElementById("myRange").value;
var value1 = 0.5 * x; //entered values manually as I don't know how to retrieve from table cells
var v1 = value1.toFixed(2);
var value2 = 5 * x;
var v2 = value2.toFixed(2);
var value3 = 2 * x;
var v3 = value3.toFixed(2);
document.getElementById('value1').innerHTML = v1;
document.getElementById('value2').innerHTML = v2;
document.getElementById('value3').innerHTML = v3;
}
</script>
</body>
</html>
If you give all the cells the same class you can access them all using .getElementsByClassName. You can also assign a value to an attribute of the cell and then access it using .getAttribute.
Please see the snippet below as an example.
function myReset() {
document.getElementById("myForm").reset();
}
function myFunction() {
var x = document.getElementById("myRange").value;
var cells = document.getElementsByClassName("value-cell");
for(var cell of cells) {
var value = cell.getAttribute('value');
cell.innerHTML = value * x;
}
}
<html>
<body onload="myFunction()">
<table>
<tr>
<td>value one</td>
<td class="value-cell" value="0.5"></td>
</tr>
<tr>
<td>value two</td>
<td class="value-cell" value="5"></td>
</tr>
<tr>
<td>value three</td>
<td class="value-cell" value="2"></td>
</tr>
</table>
<form id="myForm">
<input type="range" id="myRange" defaultvalue="1" value="1" min="0.1" max="2" step="0.1"
onclick="myFunction()">
<input type="button" onclick="myReset(); myFunction()" value="Reset">
</form>
</body>
</html>
An alternative to using .getAttribute would be to put a hidden input inside the cell and store the value there and then access it with input.value.
You could also use jQuery and make the whole thing a little cleaner.
The icky part is finding a way to iterate through the elements, in this current solution it is assuming the elements will have increasing IDs starting with "value1". Naturally if you add a class to each element you can iterate through that way, but this should suffice to demonstrate the point.
function myReset() {
document.getElementById("myForm").reset();
}
function myFunction() {
var x = document.getElementById("myRange").value;
var count = 1;
var currentElem = document.getElementById("value" + count);
while (currentElem) {
var val = (currentElem.innerText * x).toFixed(2);
currentElem.innerHTML = val;
count++;
currentElem = document.getElementById("value" + count);
}
}
<html>
<body onload="myFunction()">
<table>
<tr>
<td>value one</td>
<td class="table-val" id="value1">0.5</td>
</tr>
<tr>
<td>value two</td>
<td class="table-val" id="value2">5</td>
</tr>
<tr>
<td>value three</td>
<td class="table-val" id="value3">2</td>
</tr>
</table>
<form id="myForm">
<input type="range" id="myRange" defaultvalue="1" value="1" min="0.1" max="2" step="0.1" onclick="myFunction()">
<input type="button" onclick="myReset();myFunction()" value="Reset">
</form>
</body>
</html>
Related
I'm very new to JS and I'm trying to learn for loops and in this case, I want to turn this into a for loop if possible. I want to calculate a static number string in cell 3, times the input number in cell 4, and output the result to a new cell 5 that has been created in the loop. Any help is much appreciated
var table = document.getElementById("table");
var Row1 = table.rows[1],
cell1 = Row1.insertCell(5);
var Row2 = table.rows[2],
cell2 = Row2.insertCell(5);
var Row3 = table.rows[3],
cell3 = Row3.insertCell(5);
var Row4 = table.rows[4],
cell4 = Row4.insertCell(5);
var Row5 = table.rows[5],
cell5 = Row5.insertCell(5);
var Row6 = table.rows[6],
cell6 = Row6.insertCell(5);
var x1 = table.rows[1].cells[4].getElementsByTagName('input')[0].value;
var y1 = table.rows[1].cells[3].innerHTML;
cell1.innerHTML = y1 * x1;
var x2 = table.rows[2].cells[4].getElementsByTagName('input')[0].value;
var y2 = table.rows[2].cells[3].innerHTML;
cell2.innerHTML = y2 * x2;
var x3 = table.rows[3].cells[4].getElementsByTagName('input')[0].value;
var y3 = table.rows[3].cells[3].innerHTML;
cell3.innerHTML = y3 * x3;
var x4 = table.rows[4].cells[4].getElementsByTagName('input')[0].value;
var y4 = table.rows[4].cells[3].innerHTML;
cell4.innerHTML = y4 * x4;
var x5 = table.rows[5].cells[4].getElementsByTagName('input')[0].value;
var y5 = table.rows[5].cells[3].innerHTML;
cell5.innerHTML = y5 * x5;
var x6 = table.rows[6].cells[4].getElementsByTagName('input')[0].value;
var y6 = table.rows[6].cells[3].innerHTML;
cell6.innerHTML = y6 * x6;
These don't need to be in functions but just to make it easier to read
function createCells() {
cells = []
for (let i = 1; i < 7; i++) {
var cells[i] = table.rows[i].insertCell(5)
}
}
function calculate() {
for
let (i = 1; i < 7; i++) {
var x = table.rows[i].cells[4].getElementsByTagName('input')[0].value;
var y = table.rows[i].cells[3].innerHTML;
cells[i].innerHTML = (y * x);
}
}
A short answer using a simple for-loop is this:
Loop through every row
For each row, multiply quantity with price
Output total in same row
Since we basically always want to have a "total"-field in every row, we can add it in the HTML directly.
And since we know the position of the price-element and quantity-element, we can access them using fixed values as indices.
var rows = document.querySelectorAll("#pricetable tbody tr");
for (var i = 0; i < rows.length; ++i) {
var price = rows[i].children[3].innerHTML;
var quantity = rows[i].children[4].children[0].value;
var total = price * quantity; // Implicit type-casting to numbers
rows[i].children[5].innerHTML = total;
}
<table id="pricetable">
<thead>
<tr>
<th>Number</th>
<th>Product</th>
<th>Brand</th>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>23456789</td>
<td>Phone</td>
<td>Apple</td>
<td>6500</td>
<td>
<input type="text" size="3" value="1" />
</td>
<td></td>
</tr>
<tr>
<td>22256289</td>
<td>Phone</td>
<td>Samsung</td>
<td>6200</td>
<td>
<input type="text" size="3" value="1" />
</td>
<td></td>
</tr>
<tr>
<td>24444343</td>
<td>Phone</td>
<td>Huawei</td>
<td>4200</td>
<td>
<input type="text" size="3" value="1" />
</td>
<td></td>
</tr>
<tr>
<td>19856639</td>
<td>Tablet</td>
<td>Apple</td>
<td>4000</td>
<td>
<input type="text" size="3" value="1" />
</td>
<td></td>
</tr>
<tr>
<td>39856639</td>
<td>Tablet</td>
<td>Samsung</td>
<td>2800</td>
<td>
<input type="text" size="3" value="1" />
</td>
<td></td>
</tr>
<tr>
<td>12349862</td>
<td>Tablet</td>
<td>Huawei</td>
<td>3500</td>
<td>
<input type="text" size="3" value="1" />
</td>
<td></td>
</tr>
</tbody>
</table>
Note: When changing the position of those elements (e.g. by add a new column infront of them), their index would shift. That would make you have to update the indices in the JS-file manually.
You can make this easier for yourself by using this simple "trick":
Add specific classes to the elements (e.g. .price, .quantity, .total), allowing you to easily find them using Element.querySelector().
Note: The script only runs once, the first time the page is loaded. That means, inputting a different quantity won't update the "total"-field. For that, we need an EventListener.
Another approach
By observing the for-loop, we can see:
We access only one row for each iteration
The order in which we access each row is irrelevant
Since both these points are checked, we can use a for...of-loop (also called foreach-loop or enhanced for-loop). A for...of-loop is (in my opinion) easier to read, and tells what we checked using the list above by itself.
Note: Be wary of the difference of the for...of-loop and the for...in-loop.
Now, we could calculate the total right then and there in the loop, but thinking ahead, we want to perform the same calculation again when inputting a new quantity-value. We can reduce the duplicate code by making the calculation a Function updateRowTotal(), making the code easier to debug and understand.
To actually update the total when entering a new quantity-value, we can use an EventListener that calls a function automatically when a new value is entered into the <input>-field (by calling updateRowTotal(evt.target.closest("tr"))).
function clamp(min, value, max) {
return Math.max(min, Math.min(value, max));
}
for (let row of document.querySelectorAll("#pricetable tbody tr")) {
updateRowTotal(row);
row.querySelector("input.quantity").addEventListener("input", evt => {
// Add '/*' before this comment to "remove" this extra part
// The 5 lines below are to clamp 'value' between 'min' and 'max'
let min = parseInt(evt.target.getAttribute("min"));
let max = parseInt(evt.target.getAttribute("max"));
if (isNaN(min)) min = Number.MIN_SAFE_INTEGER;
if (isNaN(max)) max = Number.MAX_SAFE_INTEGER;
evt.target.value = clamp(min, evt.target.value, max);
// */
updateRowTotal(evt.target.closest("tr"));
});
}
function updateRowTotal(row) {
row.querySelector(".total").innerHTML = row.querySelector(".price").innerHTML * row.querySelector(".quantity").value;
}
<table id="pricetable">
<thead>
<tr>
<th>Price</th>
<th>Quantity</th>
<th>Row-Total</th>
</tr>
</thead>
<tbody>
<tr>
<td class="price">6500</td>
<td>
<input class="quantity" type="number" min="0" max="999" value="1" />
</td>
<td class="total"></td>
</tr>
<tr>
<td class="price">6200</td>
<td>
<input class="quantity" type="number" min="0" max="999" value="1" />
</td>
<td class="total"></td>
</tr>
<tr>
<td class="price">4200</td>
<td>
<input class="quantity" type="number" min="0" max="999" value="1" />
</td>
<td class="total"></td>
</tr>
<tr>
<td class="price">4000</td>
<td>
<input class="quantity" type="number" min="0" max="999" value="1" />
</td>
<td class="total"></td>
</tr>
<tr>
<td class="price">2800</td>
<td>
<input class="quantity" type="number" min="0" max="999" value="1" />
</td>
<td class="total"></td>
</tr>
<tr>
<td class="price">3500</td>
<td>
<input class="quantity" type="number" min="0" max="999" value="1" />
</td>
<td class="total"></td>
</tr>
</tbody>
</table>
Sidenote
Making the <input>-field of type="number" prevents any non-numeric character to be entered.
And since the min- and max-attributes only prevent form-submission, we have to code the value-clamping ourselves. This is easily done by reading the values of the attributes and clamping the value to their defined range. Note that we have added default values for both min and max, being the lower-most and upper-most safe integer-value.
You can use for-loops like the one given below. Looks like you are operating on numbers, so I have added a + in front of x1's and y1's assignment to implicitly type-cast them to numbers.
for(var i = 1; i <= 6; i++) {
var firstRow = table.rows[i], cell = firstRow.insertCell(5);
var x1 = +table.rows[i].cells[4].getElementsByTagName('input')[0].value;
var y1 = +table.rows[i].cells[3].innerHTML;
cell.innerHTML = y1 * x1;
}
sorry for asking simple question. I am really a beginner in Javascript. I need to access my HTML array form object in my javascript, but I don't know how to do it.
The goal is to trigger the alert in javascript so the browser will display message according to the condition in javascript. Here is my code :
checkScore = function()
{
//I don't know how to access array in HTML Form, so I just pretend it like this :
var student = document.getElementByName('row[i][student]').value;
var math = document.getElementByName('row[i][math]').value;
var physics = document.getElementByName('row[i][physics]').value;
if (parseInt(math) >= 80 ) {
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics) >= 80 ){
alert(student + " ,You are good at physics");
}
student_score.row[i][otherinfo].focus();
student_score.row[i][otherinfo].select();
}
<h2>HTML Forms</h2>
<form name="student_score" action="/action_page.php">
<table border=1>
<thead>
<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</thead>
<tbody>
<tr>
<td><input type="text" name="row[1][student]"></td>
<td><input type="number" name="row[1][math]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>
<tr>
<td><input type="text" name="row[2][student]"></td>
<td><input type="number" name="row[2][math]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" onblur="checkScore()" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
<p>If you click the "Submit" button, it will save the data.</p>
We are going to leverage few things here to streamline this.
The first is Event Listeners, this removes all javascript from your HTML. It also keeps it more dynamic and easier to refactor if the table ends up having rows added to it via javascript.
Next is parentNode, which we use to find the tr that enclosed the element that was clicked;
Then we use querySelectorAll with an attribute selector to get our target fields from the tr above.
/*This does the work*/
function checkScore(event) {
//Get the element that triggered the blur
var element = event.target;
//Get our ancestor row (the parent of the parent);
var row = element.parentNode.parentNode;
//Use an attribute selector to get our infor from the row
var student = row.querySelector("[name*='[student]']").value;
var math = row.querySelector("[name*='[math]']").value;
var physics = row.querySelector("[name*='[physics]']").value;
var otherField = row.querySelector("[name*='[otherinfo]']");
if (parseInt(math, 10) >= 80) {
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics, 10) >= 80) {
alert(student + " ,You are good at physics");
}
otherField.focus();
otherField.select();
}
/*Wire Up the event listener*/
var targetElements = document.querySelectorAll("input[name*='math'], input[name*='physics']");
for (var i = 0; i < targetElements.length; i++) {
targetElements[i].addEventListener("blur", checkScore);
}
<h2>HTML Forms</h2>
<form name="student_score" action="/action_page.php">
<table border=1>
<thead>
<tr>
<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="row[1][student]" class='student'></td>
<td><input type="number" name="row[1][math]" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>
<tr>
<td><input type="text" name="row1[2][student]"></td>
<td><input type="number" name="row[2][math]" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
Well, it follows your line of code exactly as it is (because you said you do not want to change the code too much).
<h2>HTML Forms</h2>
<form name="student_score" action="/action_page.php">
<table border=1>
<thead>
<td>Student</td>
<td>Math Score</td>
<td>Physics Score</td>
<td>Other info</td>
</thead>
<tbody>
<tr>
<td><input type="text" name="row[1][student]"></td>
<td><input type="number" name="row[1][math]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="number" name="row[1][physics]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="text" name="row[1][otherinfo]"></td>
</tr>
<tr>
<td><input type="text" name="row1[2][student]"></td>
<td><input type="number" name="row[2][math]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="number" name="row[2][physics]" onblur="checkScore(this)" min="0" max="100"></td>
<td><input type="text" name="row[2][otherinfo]"></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit">
</td>
</tr>
</tbody>
</table>
</form>
JavaScript [Edited again using part of the #Jon P code, the query selector is realy more dynamic, and the value of the "other" field you requested is commented out]
//pass element to function, in html, only add [this] in parenteses
checkScore = function (element) {
//Get our ancestor row (the parent of the parent);
var row = element.parentNode.parentNode;
//Use an attribute selector to get our infor from the row
var student = row.querySelector("[name*='[student]']").value;
var math = row.querySelector("[name*='[math]']").value;
var physics = row.querySelector("[name*='[physics]']").value;
var other = row.querySelector("[name*='[otherinfo]']");
if (parseInt(math) >= 80) {
//other.value = student + " ,You are good at mathematic";
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics) >= 80) {
//other.value = student + " ,You are good at physics";
alert(student + " ,You are good at physics");
}
otherField.focus();
otherField.select();
}
Tested :), and sorry about my english!
Try that, haven't tested it
var form = document.getElementsByName("student_score")[0];
var students = form.getElementsByTagName("tr");
for(var i = 0; i < students.length; i++){
var student = students[i].childnodes[0].value;
var math = students[i].childnodes[1].value;
var physics = students[i].childnodes[2].value;
if (parseInt(math) >= 80 ) {
alert(student + " ,You are good at mathematic");
}
if (parseInt(physics) >= 80 ){
alert(student + " ,You are good at physics");
}
}
I have the following table:
<table id="sortme">
<tr>
<td>a</td>
<td>b <input type="hidden" name="pr" value="50"/>
</td>
</tr>
<tr>
<td>c</td>
<td>d <input type="hidden" name="pr" value="20"/>
</td>
</tr>
</table>
With the following script:
$(function () {
$('#sortme tr:has(input[name="pr"])').sort(function(a, b) {
return 1 * $(a).find("input[name='pr']").val() - 1 * $(b).find("input[name='pr']").val();
}).appendTo('#sortme');
});
The table will be re-sorted so that the second row, will become the first one, since 20 < 50.
Question:
In addition to that, how can I also append an HTML block right after the [input] that was found as the lowest, and reach this result:
<table id="sortme">
<tr>
<td>c</td>
<td>d <input type="hidden" name="pr" value="20"/>
<p class="min">Min. Value</p>
</td>
</tr>
<tr>
<td>a</td>
<td>b <input type="hidden" name="pr" value="50"/>
</td>
</tr>
</table>
I guess I should add some .appendTo("input[name='pr']") command as the last row to the script, but not sure how to do it.
Edit:
While Sachin's Solution is Good, I would also like to see a solution that appends the block to the lowest value, and will be independent of the first function which sorts the table. the reason is that I might want to append the block without doing any sorting.
try this.. if you want to do it without sort:
$(function () {
var min = $("#sortme input[name='pr']:first").val()
$("#sortme input[name='pr']").each(function(){
if(parseInt($(this).val()) < parseInt(min))
min = $(this).val();
});
$('<p class="min">Min. Value</p>').insertAfter("#sortme input[name='pr'][value='" + min + "']:first");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="sortme" border="1|0">
<tr>
<td>a</td>
<td>b <input type="hidden" name="pr" value="50"/>
</td>
</tr>
<tr>
<td>c</td>
<td>d <input type="hidden" name="pr" value="20"/>
</td>
</tr>
</table>
or this with sort:
after sorting.. this will insert p tag after first input of table, as after sorting the minimum value will be on top.
$('<p class="min">Min. Value</p>').insertAfter("#sortme input:first");
Appending it before sort will not solve the purpose because you won't be very sure about where is the minimum value, in the last, in the top or somewhere in the middle.
$(function () {
$('#sortme tr:has(input[name="pr"])').sort(function(a, b) {
return 1 * $(a).find("input[name='pr']").val() - 1 * $(b).find("input[name='pr']").val();
}).appendTo('#sortme').first().find("input[name='pr']").after('<p class="min">Min. Value</p>');
});
First search the input with least value:
var minValue = Math.min.apply( null, $("input[name='pr']").map(function(){return this.value;}) );
Then append to input with this value:
.appendTo("input[value='" + minValue + "']")
Trying to self create a validation that compares Gross and Tare values in the table using jQuery validation plugin. Tare should always be smaller than Gross.
Here is the JS code:
$.validator.addMethod('lessThan', function (value, element, param) {
if (this.optional(element)) return true;
var i = parseInt(value);
var j = parseInt($(param).val());
return i <= j;
}, "Tare must less than Gross");
$('#myForm').validate({rules: {tare: {lessThan: ".gross"}}});
And my HTML:
<form id="myForm">
<table id="lineItemTable">
<thead>
<th>
<tr>
<td>Gross</td>
<td>Tare</td>
</tr>
</th>
</thead>
<tbody>
<tr>
<td><input type="text" name='gross' class="gross"/></td>
<td><input type="text" name='tare' class="tare"/></td>
</tr>
<tr>
<td><input type="text" name='gross' class="gross"/></td>
<td><input type="text" name='tare' class="tare"/></td>
</tr>
</tbody>
</table>
</form>
This code works fine when only have one row involved.
When comes two table rows, it compares the 2nd row tare value with the 1st row gross value. Apparently I want it to compare 2nd row tare value with 2nd row gross value. Also for some reason the error message shows up at the 1st row.
Here is one screen shot:
Please advise how do I change my code to make it working properly.
And here is the CDN that I am using:
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
Looking for $('.gross').val() will always retrieve the value of the first matched element (in the whole document).
Instead, look only in the row containing the element being validated:
var j = parseInt($(element).closest('tr').find(param).val());
$.validator.addMethod('lessThan', function(value, element, param) {
console.log(element);
if (this.optional(element)) return true;
var i = parseInt(value);
var j = parseInt($(element).closest('tr').find(param).val());
return i <= j;
}, "Tare must less than Gross");
$('#myForm').validate({
rules: {
tare: {
lessThan: ".gross"
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<form id="myForm">
<table id="lineItemTable">
<thead>
<th>
<tr>
<td>Gross</td>
<td>Tare</td>
</tr>
</th>
</thead>
<tbody>
<tr>
<td>
<input type="text" name='gross' class="gross" />
</td>
<td>
<input type="text" name='tare' class="tare" />
</td>
</tr>
<tr>
<td>
<input type="text" name='gross' class="gross" />
</td>
<td>
<input type="text" name='tare' class="tare" />
</td>
</tr>
</tbody>
</table>
</form>
I could really your help! I need to sum a dynamic amount of textboxes but my JavaScript knowledge is way to week to accomplish this. Anyone could help me out? I want the function to print the sum in the p-tag named inptSum.
Here's a function and the html code:
function InputSum() {
...
}
<table id="tbl">
<tbody>
<tr>
<td align="right">
<span>June</span>
</td>
<td>
<input name="month_0" type="text" value="0" id="month_0" onchange="InputSum()" />
</td>
</tr>
<tr>
<td align="right">
<span>July</span>
</td>
<td>
<input name="month_1" type="text" value="0" id="month_1" onchange="InputSum()" />
</td>
</tr>
<tr>
<td align="right">
<span>August</span>
</td>
<td>
<input name="month_2" type="text" value="0" id="month_2" onchange="InputSum()" />
</td>
</tr>
<tr>
<td align="right">
<span>September</span>
</td>
<td>
<input name="month_3" type="text" value="0" id="month_3" onchange="InputSum()" />
</td>
</tr>
</tbody>
</table>
<p id="inputSum"></p>
function InputSum() {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if(inputs[i].id.indexOf("month_") == 0)
alert(inputs[i].value);
}
}
With a little jQuery, you could do it quite easily, using the attribute starts with selector. We then loop over them, parses their values into integers and sum them up. Something like this:
function InputSum() {
var sum = 0;
$('input[id^="month_"]').each(function () {
sum += parseInt($(this).val(), 10);
});
$("#inputSum").text(sum);
}
You could even get rid of the onchange attributes on each input if you modify the code to something like this:
$(function () {
var elms = $('input[id^="month_"]');
elms.change(function() {
var sum = 0;
elms.each(function () {
sum += parseInt($(this).val(), 10);
});
$("#inputSum").text(sum);
});
});
function InputSum() {
var month_0=document.getElementById("month_0").value;// get value from textbox
var month_1=document.getElementById("month_1").value;
var month_2=document.getElementById("month_2").value;
var month_3=document.getElementById("month_3").value;
// check number Can be omitted the
alert(month_0+month_1+month_2+month_3);//show result
}