javascript with laravel blade template loop and sum - javascript

i'm trying to do calculation with my table using java-script, but i don't know how to loop it with the rest of the id. right now i can only calculate single item how to make this multiple here is the result
as you can see only id 1 get the result while id 2 is null how can i make this work here is my java script
function calc(){
var n1 = parseFloat(document.getElementById('n1').value);
var n2 = parseFloat(document.getElementById('n2').value);
var oper = document.getElementById('result').value = n1*4+n2;
}
<table id="my-table" class="table table-hover table-bordered">
<thead>
<tr >
<th class="text">NAME</th>
<th class="text">A/P</th>
<th class="text">H/W</th>
<th class="text">Result</th>
</tr>
</thead>
<tbody>
#foreach($scores as $index => $score)
<tr>
<td>{{$score->lead->student_name}} <input type="hidden" name="scores[{{$loop->index}}][id]" value="{{$score->id}}"></td>
<td style="text-align:center"><input id="n1" type="text" name="scores[{{$loop->index}}][jan_ap]" value="{{$score->jan_ap}}" class="input" autocomplete="off"></td>
<td style="text-align:center"><input id="n2" type="text" name="scores[{{$loop->index}}][jan_hm]" value="{{$score->jan_hm}}" class="input" autocomplete="off"></td>
<td style="text-align:center"><input id="result" type="text" name="scores[{{$loop->index}}][result]" value="{{$score->result}}" class="input" autocomplete="off"></td>
</tr>
#endforeach
</tbody>
</table><div class="form-group ">
<button onclick="calc(); " type="submit">Submit</button>
</div>

From chat discussion and your controller code it found that, you want to add row with some formula and save the result in results field in database. So here we come up with code
Controller save method
$scores = $request->input('scores');
foreach($scores as $row){
$score = Score::find($row['id']);
$score->jan_ap = $row['jan_ap'];
$score->jan_hm = $row['jan_hm'];
$score->result = round($row['jan_ap'] * 0.5) + ($row['result'] * 0.5);
$score->save();
}
Note: Remove your result text input fro blade template because it is not used anymore.

I am answering this with some assumptions that I will make, since its not really clear from the question.
Assumption 1:
You have this table rendered using blade that gets Data from somewhere:
<div id="myTabDiv">
<table name="mytab" id="mytab1">
<tr>
<td>col1 Val1 (has ID)</td>
<td>col2 Val2 (has jan_ap)</td>
<td>col3 Val3 (has jan_hm)</td>
<td>col4 Val4 (has result)</td>
</tr>
<tr>
<td>col1 Val1 (has ID)</td>
<td>col2 Val2 (has jan_ap)</td>
<td>col3 Val3 (has jan_hm)</td>
<td>col4 Val4 (has result)</td>
</tr>
Assumption 2: Yo have populated col 1-3 with values but you have a magical button, that when clicked calculates col4. Said button uses a JS function.
function calc(){
var table = document.getElementById("mytab1");
for (var i = 0, row; row = table.rows[i]; i++) {
//iterate through rows
//rows would be accessed using the "row" variable assigned in the for loop
for (var j = 0, col; col = row.cells[j]; j++) {
//iterate through columns
//columns would be accessed using the "col" variable assigned in the for loop
//here you can do things like saying sum col[1] + col[2] and then input result in col[3]
}
}
}

Related

How to perform operations on selected rows in checkbox in a table in HTML

I have a table and I want to perform some operations(suppose doing output of selected rows in alert) on the rows which the user have checked on.
Following is my approach which is failing miserably-
<html>
<head>
<title>Introduction</title>
<script>
function kro(){
var x = document.getElementsByName('checks');
for (var i = 0;i < x.length;i++){
if(x[i].checked == 1)
var selecteddata+=x[i].value+"\n";
}
alert(selecteddata)
}
</script>
</head>
<body>
<table>
<thead>
<tr>
<th>UserName</th>
<th>Post</th>
<th>Comments</th>
<th>Select</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ram</td>
<td>Sahi hai</td>
<td>Ravan:No</td>
<td><input type = "checkbox" name = "checks" id='one'/> </td>
</tr>
<tr>
<td>Ravan</td>
<td>Kidnap done</td>
<td>Ram:I'll kill you</td>
<td><input type = "checkbox" name = "checks" id='two'/> </td>
</tbody>
<p id = "check" ></p>
<button onclick="kro()">
Result
</button>
</body>
</html>
Following is my table-
I want to perform further operations on the selected row ,in the code ,I just want to output the selected rows using alert.
How to do that?
Expected Output-
if first row is checked then
Ram Sahi hai Ravan:No
var selecteddata+=x[i].value+"\n"; line will throw an error, So declare the variable outside the for loop. Also you need to set a value to checkbox otherwise it will so on
To get the content from all the td get the parent of the checkbox and get the closest tr. Then get text from each of the td and add it in a local variable of the if block
function kro() {
var x = document.getElementsByName('checks');
var selecteddata = '';
for (var i = 0; i < x.length; i++) {
if (x[i].checked) {
let _tt = '';
x[i].closest('tr').querySelectorAll('td').forEach(function(item) {
_tt += item.textContent.trim();
})
selecteddata += _tt + "\n";
}
}
alert(selecteddata)
}
<table>
<thead>
<tr>
<th>UserName</th>
<th>Post</th>
<th>Comments</th>
<th>Select</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ram</td>
<td>Sahi hai</td>
<td>Ravan:No</td>
<td><input type="checkbox" name="checks" id='one' value='test1' /> </td>
</tr>
<tr>
<td>Ravan</td>
<td>Kidnap done</td>
<td>Ram:I'll kill you</td>
<td><input type="checkbox" name="checks" id='two' value='test2' /> </td>
</tbody>
<p id="check"></p>
<button onclick="kro()">
Result
</button>
You define and concat to the variable wrong.
should be
var foo = ''; // declare outside of loop
for (var i=0; i<5; i++) {
foo += i + '\n' // concat to string
}
console.log(foo) //display it
Other way people would do it is with an array and joining it at the end
var foo = []; // declare outside of loop
for (var i=0; i<5; i++) {
foo.push(i) // add to array
}
console.log(foo.join('\n')) //display it by joining the array items

How to get table row index when the column textbox value change using jQuery

I want to get row index and text box values when the table price text box value changes. At the moment I'm getting some undefined value.
HTML
<table class="table table-striped">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" class="form-control product">
</td>
<td>
<input type="text" oninput="javascript:GetValue(this);" class="form-control price">
</td>
</tr>
</tbody>
</table>
JavaScript
function GetValue(oTextBox) {
var price = oTextBox.value;
var product = oTextBox.parent().prev().innerHTML.value;
var rowindex = oTextBox.closest('tr').index();
}
I get this error:
TypeError: oTextBox.parent is not a function
var product = oTextBox.parent().prev().innerHTML.value;
You need to wrap oTextBox in $ in order to use jQuery methods. That's because oTextBox ... or ... this is a DOM element and not a jQuery object. Thus:
var product = oTextBox.parent().prev().innerHTML.value;
Should be:
var product = $(oTextBox).parent().prev().find('input').val();
And:
var rowindex = oTextBox.closest('tr').index();
Should be:
var rowindex = $(oTextBox).closest('tr').index();
SUGGESTION
I would encourage you to not use inline JS:
<input type="text" class="form-control price">
Then your jQuery would be:
$(function() {
$('input.price').on('input', function() {
var price = this.value;
var product = $(this).parent().prev().find('input').val();
var rowindex = $(this).closest('tr').index();
//....
});
});
Replace oTextBox in the function by $(oTextBox) and then you can use html() instead of innerHTML, like so
$(oTextBox).parent().prev().html()

How to set value in dynamically added rows form using jquery?

I have a form in php with dynamically added rows (after clicking button the row is added). I want to fill the field with value "xx" and i want to do it in jquery.
This loop create the dynamically added rows in jquery. I want to fill added fields with value "xx":
while($personsArrayLength>2){
echo '
<script>
$(document).ready(function(){
var i = 2;
var rowTemplate2 = jQuery.format($("#template2").html());
rowTemplate2.value = "xx";
addRow2();
function addRow2(){
var ii = i++;
$("#app_here2").append(rowTemplate2(ii));
$("#delete_" + ii).click(function(){
$("#row_" + ii).remove();
});
}
});
</script>
';
Here is html for that:
function addRows2(){
global $personsError_css;
$personsArray = $_POST['persons'];
JB_var_dump($_POST['whichRow']);
$html = '<table id="template2" align="right" style="display:none; ">
<tr id="row_{0}">
<td><input type="text" size="52" id="persons" name="persons[]" maxlength="100"></td>
<td><img src="/../_img/row_del.png" id="delete_{0}" alt="usun"></td>
</tr>
</table>
<table id="list2" style="margin-left:200px;">
<thead >
<tr>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" size="52" name="persons[]" maxlength="100" style="'.$personsError_css.';" value="'.$personsArray[1].'"></td>
<td></td>
</tr>
<tr>
<td colspan="2" id="app_here2"></td>
</tr>
</tbody>
</table>';
return $html;
}
This is properly filled form
In this epty fields I want to add values "xx"
Sorry for my english.
How can i set values in added rows? What i should change in my code?
Thanks for help.
Change your 'addRow2' to this:
function addRow2(){
var ii = i++;
$("#app_here2").append(rowTemplate2(ii));
//UPDATE: var rowTemplate2 is not a jQuery Object, as i thought
$("#template2").find("input:empty").val("xx");; // added this row
$("#delete_" + ii).click(function(){
$("#row_" + ii).remove();
});
}

incrementing the value of a input field in the cloned row

1)here i'm doing clone of a row...but this code is working only in eclipse [ ie ,cloning is working ] and it is also not working in any browsers.
2)What is the solution to get the values of text boxes in the cloned rows having same name, and insert into the database using jsp and servlet?
how can i get those values with same name
3)i have servlet code to get only single value from jsp
String address_seq_num =request.getParameter("address_seq_num");
how can i get the value of address seq number in the cloned row fromjsp to servlet to insert into the next row of a table in the database.
4)if i mention "DOCUMENT TYPE" to this code ,it will not work in eclipse also.....
please guide me...
JavaScript
function clonetable() {
var x=document.getElementById("main_table"); //get the table
var rowCount = x.rows.length;
var row = document.getElementById("table_row_clone"); // find row to copy
var table = document.getElementById("table_body"); // find table to append to
var clone = row.cloneNode(true); // copy children too
var tb1 = clone.document.getElementById("asn");//here i'm incrementing the value
tb1.value=rowCount+1;//of "address seq num " in the cloned row
clone.id = "abc"; // change id or other attributes/contents
table.appendChild(clone); // add new row to end of table
}
function deltable() {
var x = document.getElementById("main_table"); //get the table
var rowCount = x.rows.length;
if (rowCount > 1) {
x.deleteRow(rowCount - 1);
} //delete the last row
}
HTML
<table id="main_table" align="center" style="width:75%">
<tbody id="table_body">
<tr id="table_row_clone">
<td>
<table align="center" style="width:100%">
<tr>
<td align="center">
<div style="border:3px solid silver;border-radius:5px;background-color:grey">
<table width="100%">
<tr>
<th align="center">Address Details</th>
</tr>
</table>
</div>
</td>
</tr>
<tr>
<td>
<div style="border:3px solid silver;border-radius:5px;background-color:#1E90FF">
<table align="center" style="width:99%">
<tr style="background-color:#1E90FF">
<td style="width:35%">
<table width="100%">
<tr id="slrow">
<td style="width:43%">Address Seq Num</td>
<td>
<input id="asn" style="width:60px" name="address_seq_num" type="text" value="1" readonly>
</td>
</tr>
</table>
</td>
<td width="49%" align="right">
<input style="width:80%" type="text" value="Reg.office/Primary Office">
</td>
<td align="right">
<input style="width:30px" type="button" value="+" onclick="clonetable()">
<input style="width:30px" type="button" value="-" onclick="deltable()">
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</td>
</tr>
</tbody>
Per your HTML (which is messy, by the way) you can increment that textbox's value with something like:
var tb = document.getElementById("asn");
tb.value = parseInt(tb.value, 10) + 1;
The trick is you have to cast the textbox's value into a number, which is what parseInt is doing in that example.
Note that the above snippet will give you "NaN" in the textbox if the value is not a valid number - it's not doing any data validation at all.

How can I populate a table's cell through JavaScript code?

I have a table as below. I have to populate the "Amount" field using the "Buy Quantity" and "Market Price" field. Amount = Buy Quantity*Market Price. I am doing something as -
<script>
function populate() {
var rows = document.getElementById("mytable").getElementsByTagName("tr");
for ( var i = 1; i <= rows.length; i++) {
cells = rows[i].getElementsByTagName("td");
for ( var j = 0; j <= cells.length; j++) {
if (j == 1) {
var num1 =parseFloat(cells[1].childNodes[0].value);
var num2 =parseFloat(cells[2].childNodes[0].data);
var num3=num1 * num2;
cells[3].childNodes[0].value = num3.toString();
}
}
}
}
</script>
I can get the values of column1 and column2, but the value in last column is not getting populated. The last line does not seem to work.
cells[3].childNodes[0].value = num3.toString();
What should I change?
The below html code is part of my .jsp file.
<form action="BuyServlet">
<table border="1" cellpadding="5" id="mytable">
<tr>
<th>Stock Name</th>
<th>Buy Quantity</th>
<th>Market Price</th>
<th>Amount</th>
</tr>
<tr>
<td>Stock Name</td>
<td><input type="text" name="quantity" onblur="populate()"></td>
<td>122</td>
<td><input type="text" name="amount">
</d>
</tr>
<tr>
<td>Stock Name</td>
<td><input type="text" name="quantity" onblur="populate()"></td>
<td>111</td>
<td><input type="text" name="amount"></td>
</tr>
</table>
</form>
Basically you are getting the value from the text box (best quantity) and you are using data to get the value of the Market price(better use innerText)
try this (Replace with your code inside loop)
var num1 =parseFloat(cells[1].childNodes[0].value);
var num2 =parseFloat(cells[2].innerText);
var num3=num1 * num2;
cells[3].innerText = num3.toString();
Your code is in need of improvement. In your table, you should have a thead and a tbody sections. This will make it more accessible and easier to ingore the heading row.
<table border="1" cellpadding="5" id="mytable">
<thead>
<tr>
<th>Stock Name</th>
<th>Buy Quantity</th>
<th>Market Price</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td>Stock Name</td>
<td><input type="text" name="quantity"></td>
<td>122</td>
<td><input type="text" name="amount"></td>
</tr>
<tr>
<td>Stock Name</td>
<td><input type="text" name="quantity"></td>
<td>111</td>
<td><input type="text" name="amount"></td>
</tr>
</tbody>
</table>
</form>
Now with the code, you should be adding the onblur with code, not hardcoded. You are looping through the cells, there is no reason for that. Also there is no need to loop every row when the table is changed. Just calculate the one that changed! Using childNodes can be tricky because of whitespace differences in browsers. Run this code after the table has been rendered.
(function () {
var table = document.getElementById("mytable");
var tbody = table.getElementsByTagName("tbody")[0];
var rows = tbody.getElementsByTagName("tr");​​​​​​​​​
function populateRow (index, addBlurEvent) {
var row = rows[index];
var cells = row.getElementsByTagName("td")
var textboxes = row.getElementsByTagName("input");
var amountTextbox = textboxes[0];
var totalTextbox = textboxes[1];
var costCell = cells[2];
var amount = amountTextbox.value.length>0 ? parseFloat(amountTextbox.value) : 0;
var cost = parseFloat(costCell.innerHTML);
var total = amount * cost;
totalTextbox.value = total;
if (addBlurEvent) {
amountTextbox.onblur = function () { populateRow(index, false); };
}
}
for (i=0;i<rows.length;i++) {
populateRow(i, true);
}
}());
The running fiddle of the above code
​
I think the error is due to spelling mistake - you have childnodes instead of childNodes on "cells[3].childnodes[0].value = num3.toString();"
Check this fiddle - http://jsfiddle.net/VwU7C/

Categories