JavaScript calculated field - javascript

I just can't see what am I doing wrong... It doesn't calculate the "stunden" field.
There is some small mistake from my side and I just can't see it.
EDITED: now all is working as it should
$(document).ready(function(){
$('.item').keyup(function(){
var starts = 0;
var ends = 0;
var stunden = 0;
if (!isNaN($(this).find(".starts").val())) {
starts = $(this).find(".starts").val();
}
if (!isNaN($(this).find(".ends").val())) {
ends = $(this).find(".ends").val();
}
stunden = ends - starts;
$(this).find(".stunden").val(stunden);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<table id="t1" class="table table-hover">
<tr>
<th class="text-center">Start Time</th>
<th class="text-center">End Time</th>
<th class="text-center">Stunden</th>
</tr>
<tr id="row1" class="item">
<td><input name="starts[]" class="starts form-control" ></td>
<td><input name="ends[]" class="ends form-control" ></td>
<td><input name="stunden[]" class="stunden form-control" readonly="readonly" ></td>
</tr>
<tr id="row2" class="item">
<td><input name="starts[]" class="starts form-control" ></td>
<td><input name="ends[]" class="ends form-control" ></td>
<td><input name="stunden[]" class="stunden form-control" readonly="readonly" ></td>
</tr>
</table>
</div>

The problem is that you are recalculating when a key is pressed in the .stunden fields, so you should move the event to the other inputs, or the parent row. You'll need something like this.
$('.item').keyup(function(){
var starts = 0;
var ends = 0;
var stunden = 0;
if (!isNaN($(this).find(".starts").val())) {
starts = $(this).find(".starts").val();
}
if (!isNaN($(this).find(".ends").val())) {
ends = $(this).find(".ends").val();
}
stunden = starts - ends;
$(this).find(".stunden").val(stunden);
});

Let me try your original keyup code .ends ,I just want to explain how is work below code
call .starts ,we currently in tr>td>input ,so need backup to tr by parent() then we find .starts inside its elements.As also .ends
find .studen is also in state tr>td>input ,so backup to td and go next td by next() then find .studen .
$(document).ready(function(){
$('.ends').keyup(function(){
var starts = 0;
var ends = 0;
var stunden = 0;
if (!isNaN($(this).parent().parent().find(".starts").val())) {
starts = $(this).parent().parent().find(".starts").val();
}
if (!isNaN($(this).parent().parent().find(".ends").val())) {
ends = $(this).parent().parent().find(".ends").val();
}
stunden = starts - ends;
$(this).parent().next().find('.stunden').val(stunden);
});
});

Related

Javascript function to calculate window areas in a table

I'm just working on a simple calculator for a small project of mine. I'm just hoping to get help with my calculatArea1 function.
I'll attach a few images showing the webpage, html code, and Javascript.
The html starts with a empty row with 3 cells so the user can add in the height and width of the window.
Then, there's a button that allows the user to add a new row/window. This is all working fine.
The problem I'm having is, whenever I add multiple rows, then start adding in the width & height then click calculate it will only calculate the top row.
I though I might add also, if I start fresh with one row, then add the height & width, then click calculate. Then, click add window, then add the width & height, then calculate again. it works.
I just want to be able to add in as many rows as I need, then add in the data, then click calculate.
Any suggestions would be much appreciated, cheers!
HTML
<table id="table1">
<tr>
<th>Height</th>
<th>Width</th>
<th>Area</th>
</tr>
<tr>
<td><input class="height" type="text"></td>
<td><input class="width" type="text"></td>
<td><div class="area"></div></td>
</tr>
</table>
This is my Javascript functions
function addWindow1() {
var table1 = document.getElementById("table1");
var row1 = table1.insertRow(1);
var cell1 = row1.insertCell(0);
var cell2 = row1.insertCell(1);
var cell3 = row1.insertCell(2);
cell1.innerHTML = '<input class="height" type="text">';
cell2.innerHTML = '<input class="width" type="text">';
cell3.innerHTML = '<div class="area"></div>';
};
function calculateArea1() {
var table1 = document.getElementById("table1");
for(var i = 0; row = table1.rows[i]; i++){
var height = document.querySelector('.height').value;
var width = document.querySelector('.width').value;
var area = document.querySelector('.area');
var areaResult = height * width;
area.innerHTML = areaResult;
};
};
This is what happens if I add multiple rows first, then add in the width & height, then click calculate
go to the add window button and add, onclick="addNewWindow()" then add this function
function addNewWindow(){
let table = document.querySelectot('#table1');
let window = `
<tr>
<td><input type="number" class="height"></td>
<td><input type="number" class="width"></td>
<td><input type="number" class="window" disabled style="user-select: select-all"></td>
</tr>
`;
table.insertAdjacentHTML('beforeend', window)
}
then add the calculation functionality
var hinputs = document.querySelectorAll('.height');
var winputs = document.querySelectorAll('.width');
hinputs.foreach(h=>{
h.addEventListener('change', ()=>{
let width = h.parentElement.querySelector('.width');
let window = h.parentElement.querySelector('.window');
if(width.value !== ""){
calculate(width.value, h.value, window )
}
})
})
winputs.foreach(w=>{
w.addEventListener('change', ()=>{
let height = w.parentElement.querySelector('.height ');
let window = w.parentElement.querySelector('.window');
if(height.value !== ""){
calculate(w.value, height.value, window)
}
})
})
function calculate(w, h, result){
result.value = w*h;
}
DEMO:
function addNewWindow() {
let table = document.querySelector('#table');
let window = `
<tr>
<td><input type="number" class="height"></td>
<td><input type="number" class="width"></td>
<td><input type="number" class="window" disabled style="user-select: select-all"></td>
</tr>
`;
table.insertAdjacentHTML('beforeend', window)
}
var hinputs = document.querySelectorAll('.height');
var winputs = document.querySelectorAll('.width');
hinputs.forEach(h => {
h.addEventListener('input', () => {
let width = h.parentElement.parentElement.querySelector('.width');
let window = h.parentElement.parentElement.querySelector('.window');
if (width.value !== "") {
calculate(width.value, h.value, window)
}
})
})
winputs.forEach(w => {
w.addEventListener('input', () => {
let height = w.parentElement.parentElement.querySelector('.height');
let window = w.parentElement.parentElement.querySelector('.window');
if (height.value !== "") {
calculate(w.value, height.value, window)
}
})
})
function calculate(w, h, result) {
result.value = w * h;
}
<table id="table">
<tr>
<td><input type="number" class="height"></td>
<td><input type="number" class="width"></td>
<td><input type="number" class="window" disabled style="user-select: select-all"></td>
</tr>
<tr>
<td><input type="number" class="height"></td>
<td><input type="number" class="width"></td>
<td><input type="number" class="window" disabled style="user-select: select-all"></td>
</tr>
</table>
<button onclick="addNewWindow()">add</button>
you can use ".innerHTML +=" or .insertAdjacentHTML('beforeend', '<div></div>');
but innerHTML removes the old inputs' values because it gets the old value and add to it your code then replace it with the current HTML so all manually applied values get removed, so use inserting beforeend to do it:
let table = document.querySelectot('#table1');
let window = `
<tr>
<td><input type="number" class="height"></td>
<td><input type="number" class="width"></td>
<td><input type="number" class="window" disabled style="user-select: select-all"></td>
</tr>
`;
table.insertAdjacentHTML('beforeend', window)
You are only getting one element with querySelector inside the calculateArea1 function. You should loop over every row and update the area with the values of width and height of that row.
One way to do this is to give a class (lets say data) to rows that contain the width, height and area cells then loop over all elements with that data class and access the cells inside it with a querySelector.
You can simplify your addWindow1 function to this:
function addWindow1() {
const row1 = table1.insertRow(1)
row1.className = 'data'
row1.innerHTML = `
<td><input class="height" type="text" /></td>
<td><input class="width" type="text" /></td>
<td><div class="area"></div></td>
`
}
Then update your calculateArea1 function as follows:
function calculateArea1() {
const data = document.querySelectorAll('.data')
for (let i = 0; i < data.length; i++) {
const height = data[i].querySelector('.height').value
const width = data[i].querySelector('.width').value
data[i].querySelector('.area').textContent = height * width
}
}
Here is a working example:
const add = document.getElementById('add')
const calc = document.getElementById('calc')
const table1 = document.getElementById('table1')
add.addEventListener('click', addWindow1)
calc.addEventListener('click', calculateArea1)
function addWindow1() {
const row1 = table1.insertRow(1)
row1.className = 'data'
row1.innerHTML = `
<td><input class="height" type="text" /></td>
<td><input class="width" type="text" /></td>
<td><div class="area"></div></td>
`
}
function calculateArea1() {
const data = document.querySelectorAll('.data')
for (let i = 0; i < data.length; i++) {
const height = data[i].querySelector('.height').value
const width = data[i].querySelector('.width').value
data[i].querySelector('.area').textContent = height * width
}
}
<button id="add">add</button>
<button id="calc">calc</button>
<table id="table1">
<tr>
<th>Height</th>
<th>Width</th>
<th>Area</th>
</tr>
<tr class="data">
<td><input class="height" type="text" /></td>
<td><input class="width" type="text" /></td>
<td>
<div class="area"></div>
</td>
</tr>
</table>
In the for loop, you should select the width/height from the current row instead of from the DOM.
// select the first item with class `height` in the DOM => not what you want
var height = document.querySelector('.height').value;
// this should work
var height = row.querySelector('.height').value;

Rewriting JavaScript code with consequent numbers in the names of ids

I'm trying to apply a function to input field with ids that contain consequent numbers (ie. price1, price2, price3), etc.
There's no problem with the first row of field that are defined for a start. But further input fields are dynamically added by a jQuery function and their number is not known in advance.
I hoped it would be an easy loop to apply:
var i=1;
$("#quantity"+i).keyup(function() {
var price= $("#price"+i).val();
var quantity= $(this).val();
var value= price*quantity;
var value=value.toFixed(2); /* rounding the value to two digits after period */
value=value.toString().replace(/\./g, ',') /* converting periods to commas */
$("#value"+i).val(value);
});
So far so good - the outcome of the multiplication properly displays in the id="value1" field after the "quantity" field is filled up.
Now further fields should follow the pattern and calculate the value when the quantity is entered - like this:
[price2] * [quantity2] = [value2]
[price3] * [quantity3] = [value3]
etc.
So the code follows:
$('#add_field').click(function(){ /* do the math after another row of fields is added */
var allfields=$('[id^="quantity"]');
var limit=(allfields.length); /* count all fields where id starts with "quantity" - for the loop */
for (var count = 2; count < limit; count++) { /* starting value is now 2 */
$("#quantity"+count).keyup(function() {
var cena = $("#price"+count).val();
var quantity= $("#quantity"+count).val();
var value= price*quantity;
var value=value.toFixed(2);
value=value.toString().replace(/\./g, ',')
$("#value"+count).val(value);
});
}
});
The problem is that all further "value" fields are only calculated when "quantity2" is (re)entered and the "value2" is not calculated at all.
I guess there's a mistake while addressing fields and/or triggering the calculation.
How should I correct the code?
Just in case the "add_field" function is needed to solve the problem:
$(document).ready(function(){
var i=1;
$('#add_field').click(function(){
i++;
$('#offer').append('<tr id="row'+i+'">
<td><input type="text" name="prod_num[]" id="prod_num'+i+'" placeholder="Product number (6 digits)"></td><td><input type="text" name="prod_name[]" disabled></td>
<td><input type="text" name="cena[]" id="price'+i+'" placeholder="Enter your price"></td>
<td><input type="text" name="quantity[]" id="quantity'+i+'" placeholder="Enter quantity"></td>
<td><input type="text" name="value[]" id="value'+i+'" disabled></td>
<td><button type="button" name="remove_field" id="'+i+'" class="button_remove">X</button></td></tr>');
});
Incrementing IDs is a lot more trouble than it is worth, especially when you start removing rows as well as adding them.
This can all be done using common classes and traversing within the specific row instance.
To account for future rows use event delegation.
Simplified example:
// store a row copy on page load
const $storedRow = $('#myTable tr').first().clone()
// delegate event listener to permanent ancestor
$('#myTable').on('input', '.qty, .price', function(){
const $row = $(this).closest('tr'),
price = $row.find('.price').val(),
qty = $row.find('.qty').val();
$row.find('.total').val(price*qty)
});
$('button').click(function(){
// insert a copy of the stored row
// delegated events will work seamlessly on new rows also
const $newRow = $storedRow.clone();
const prodName = 'Product XYZ';// get real value from user input
$newRow.find('.prod-name').text(prodName)//
$('#myTable').append($newRow)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Add row</button>
<table id="myTable">
<tr>
<td class="prod-name">Product 1</td>
<td>Qty:<input type="number" class="qty" value="0"></td>
<td>Price:<input type="number" class="price" value="0"></td>
<td>Total:<input type="text" class="total" value="0" readonly></td>
</tr>
<tr>
<td class="prod-name">Product 2</td>
<td>Qty:<input type="number" class="qty" value="0"></td>
<td>Price:<input type="number" class="price" value="0"></td>
<td>Total:<input type="text" class="total" value="0" readonly></td>
</tr>
</table>
Understanding Event Delegation
The first thing to consider is that you can get the length of a selector. So for example:
var count = $("input").length;
If there is one, value here would be 1. if there are four, the value would be 4.
You can also use .each() option to itereate each of the items in the selector.
$('#add_field').click(function(){
var allFields = $('[id^="quantity"]');
allFields.each(function(i, el){
var c = i + 1;
$(el).keyup(function() {
var price = parseFloat($("#price" + c).val());
var quantity = parseInt($(el).val());
var value = price * quantity;
value = value.toFixed(2);
value = value.toString().replace(/\./g, ',');
$("#value" + c).val(value);
});
});
});
You could also create relationship based on the ID itself.
$(function() {
function calcTotal(price, qnty) {
return (parseFloat(price) * parseInt(qnty)).toFixed(2);
}
$('#add_field').click(function() {
var rowClone = $("#row-1").clone(true);
var c = $("tbody tr[id^='row']").length + 1;
rowClone.attr("id", "row-" + c);
$("input:eq(0)", rowClone).val("").attr("id", "prod_num-" + c);
$("input:eq(1)", rowClone).val("").attr("id", "price-" + c);
$("input:eq(2)", rowClone).val("").attr("id", "quantity-" + c);
$("input:eq(3)", rowClone).val("").attr("id", "value-" + c);
$("button", rowClone).attr("id", "remove-" + c);
rowClone.appendTo("table tbody");
});
$("table tbody").on("keyup", "[id^='quantity']", function(e) {
var $self = $(this);
var id = $self.attr("id").substr(-1);
if ($("#price-" + id).val() != "" && $self.val() != "") {
$("#value-" + id).val(calcTotal($("#price-" + id).val(), $self.val()));
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add_field">Add Field</button>
<br />
<h2>Product</h2>
<table>
<thead>
<tr>
<td>Number</td>
<td>Name</td>
<td>Price</td>
<td>Quantity</td>
<td>Total</td>
<td></td>
</thead>
<tbody>
<tr id="row-1">
<td><input type="text" name="prod_num[]" id="prod_num-1" placeholder="Product number (6 digits)"></td>
<td><input type="text" name="prod_name[]" disabled></td>
<td><input type="text" name="cena[]" id="price-1" placeholder="Enter your price"></td>
<td><input type="text" name="quantity[]" id="quantity-1" placeholder="Enter quantity"></td>
<td><input type="text" name="value[]" id="value-1" disabled></td>
<td><button type="button" name="remove_field" id="remove-1" class="button_remove">X</button></td>
</tr>
</tbody>
</table>

Dragging a html table column value and increment the column value by 1 in java script

I need to increment an html table column value by 1.
For example, I have three columns in the table and the column value for the first row is 1, the second should be 2 etc.
So, If I have Roll No column with first column value is 1 then the next two rows Roll No value should be 2 and 3.
The following script does not work.
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction() {
//document.getElementById('info').innerHTML = "";
var myTab = document.getElementById('sample_table');
var rollNo=document.getElementById('input2').value;
// LOOP THROUGH EACH ROW OF THE TABLE AFTER HEADER.
var count=0;
for (var i = 1; i < myTab.rows.length; i++) {
// GET THE CELLS COLLECTION OF THE CURRENT ROW.
var objCells = myTab.rows.item(i).cells;
// LOOP THROUGH EACH CELL OF THE CURENT ROW TO READ CELL VALUES.
for (var j = 0; j < objCells.length; j++) {
count++;
//alert('hi'+count);
if(count>1){
myTab.rows[i].cells[j+1].innerHTML=rollNo+1;
}
}
}
}
</script>
</head>
<body onload="myFunction()">
<table id='sample_table'>
<tr>
<th> Name</th>
<th> Roll No</th>
</tr>
<tr>
<td><input id='input1' value='abc' readonly></td>
<td><input id='input2' value='1' ></td>
</tr>
<tr>
<td><input id='input3' value='def' readonly></td>
<td><input id='input4' ></td>
</tr>
<tr>
<td><input id='input5' value='xyz' readonly></td>
<td><input id='input6' ></td>
</tr>
</table>
</body>
</html>
You can get all the inputs in a column using querySelectorAll, like this:
document.addEventListener('DOMContentLoaded', function() {
// Collects all the inputs from the 2nd column
const inputs = document.querySelectorAll('#sample_table td:nth-child(2) input');
// Get the value of the first input in the collection, and convert it to number
const first = +inputs[0].value;
// Iterate through the inputs in the collection excluding the first one
for (let n = 1, eN = inputs.length; n < eN; n++) {
inputs[n].value = first + n;
}
});
<table id="sample_table">
<tr>
<th> Name</th>
<th> Roll No</th>
</tr>
<tr>
<td><input id="input1" value="abc" readonly></td>
<td><input id="input2" value="5"></td>
</tr>
<tr>
<td><input id="input3" value="def" readonly></td>
<td><input id="input4"></td>
</tr>
<tr>
<td><input id="input5" value="xyz" readonly></td>
<td><input id="input6"></td>
</tr>
</table>
If the column of the inputs is changed, the number in nth-child() can be changed to point to the correct column. This indexing is 1-based.
I'm guessing something like
rowspan="2"
or
colspan="2"
but we need the code the image is good for reference but we need something to work with.

How to access HTML array object in javascript?

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");
}
}

jQuery dynamic content calculate

My code is working perfectly with static part, but when i add a new row it won't calculate the field. What am i doing wrong?
It should calculate also the dynamic fields which are added via Add Row button
Live DEMO
<div class="container">
<table id="t1" class="table table-hover">
<tr>
<th class="text-center">Start Time</th>
<th class="text-center">End Time</th>
<th class="text-center">Stunden</th>
<th> <button type="button" class="addRow">Add Row</button></th>
</tr>
<tr id="row1" class="item">
<td><input name="starts[]" class="starts form-control" ></td>
<td><input name="ends[]" class="ends form-control" ></td>
<td><input name="stunden[]" class="stunden form-control" readonly="readonly" ></td>
</tr>
</table>
</div>
js
$(document).ready(function(){
$('.item').keyup(function(){
var starts = $(this).find(".starts").val();
var ends = $(this).find(".ends").val();
var stunden;
s = starts.split(':');
e = ends.split(':');
min = e[1]-s[1];
hour_carry = 0;
if(min < 0){
min += 60;
hour_carry += 1;
}
hour = e[0]-s[0]-hour_carry;
min = ((min/60)*100).toString()
stunden = hour + "." + min.substring(0,2);
$(this).find(".stunden").val(stunden);
});
// function for adding a new row
var r = 1;
$('.addRow').click(function () {
if(r<10){
r++;
$('#t1').append('<tr id="row'+ r +'" class="item"><td><input name="starts[]" class="starts form-control" ></td><td><input name="ends[]" class="ends form-control" ></td><td><input name="stunden[]" class="stunden form-control" readonly="readonly" ></td></tr>');
}
});
// remove row when X is clicked
$(document).on("click", ".btn_remove", function () {
r--;
var button_id = $(this).attr("id");
$("#row" + button_id + '').remove();
});
});
The best thing would be to use the .on() event which is used to attach one or more event handlers to the element:
$(document).on('keyup', '.item',function(){
//your code
}
When you dynamically add a new row to your table, the "keyup" event wont automatically be bound to it. Essentially you need to wrap the "keyup" event binding into a function, then call it after you've added the new row on. Something along the lines of:
function rebindKeyup(){
$('.item').keyup(function(){
// Key up logic
}
}

Categories

Resources