How to iterate changing values onkeyup using jquery? - javascript

I have a problem in my jquery/code where the id's capturing with my jquery code is an array.
Here's the snippet code.
Here's my jquery.
<script type="text/JavaScript">
$(document).ready(function()
{
$('input').keyup(function()
{
$('.total_fabi').each(function() {
var answer = parseFloat($('.req').val()) * parseInt($('.was_perc').val());
$('.total_fabi').html(answer);
});
});
});
Here's the html generated code.
<table align='center' width='100%' border='1'>
<thead style='background-color: #900; color: #FFF;'>
<th>Description</th>
<th>Estimated Cost</th>
<th>Req'd Qty</th>
<th>Wastage %</th>
<th>Total</th>
</thead>
<tbody>
<!-- This values are SQL generated inside While.. -->
<!-- Values generated by sql are under Description, Estimated Cost, Wastage-->
<!-- i Need to calculate the total using keyup by multiplying req'd qty * wastage% -->
<tr bgcolor='#FFF'>
<td>FABRICATION PER LM</td>
<td align='center'>200</td>
<td align='center'><input type='text' size='3' name='req[]' class='req'></td>
<td align='center'><input type='hidden' name='was_perc[]' value='7' class='was_perc'>7</td>
<td align='right'>
<font color='#900'>
<span id='total_fabi'>0</span>
<input type='hidden' name='total_fabi' id='total_fabi' style='border: none;' size='6' readonly='readonly'>
</font>
</td>
</tr>
<tr bgcolor='#E3E4FA'>
<td>INSTALLATION PER LM</td>
<td align='center'>200</td>
<td align='center'><input type='text' size='3' name='req[]' class='req'></td>
<td align='center'><input type='hidden' name='was_perc[]' value='15' class='was_perc'>15</td>
<td align='right'>
<font color='#900'>
<span class='total_fabi'>0</span>
<input type='hidden' name='total_fabi' id='total_fabi' style='border: none;' size='6' readonly='readonly'>
</font>
</td>
</tr>
<!-- Here's the while Ends..--->
<tr>
<td colspan='4' align='right'>Total Fabrication & Installation</td>
<td align='right'>
<!-- This part where $total+=$total_fabi -->
</td>
</tr>
</tbody>
</table>
Here's the actual PHP code.
<table align='center' width='100%' border='1'>
<thead style='background-color: #900; color: #FFF;'>
<th>Description</th>
<th>Estimated Cost</th>
<th>Req'd Qty</th>
<th>Wastage %</th>
<th>Total</th>
</thead>
<tbody>
<?php
$total_non = 0;
$sel_fabi = mysql_query("SELECT * FROM tbllabor") or die (mysql_error());
while($non = mysql_fetch_array($sel_fabi)){
$desc_fabi = $non['desc'];
$est_cost = $non['est_cost'];
$was_perc = $non['wastage_perc'];
$was_perc = $was_perc * 100;
//$total_fabi = $req * $was_perc;
echo "<tr bgcolor='".$colors[$c++ % 2]."'>";
echo " <td>$desc_fabi</td>
<td align='center'>$est_cost</td>
<td align='center'><input type='text' size='3' name='req[]' class='req'></td>
<td align='center'><input type='hidden' name='was_perc[]' value='$was_perc' class='was_perc'>$was_perc</td>
<td align='right'>
<font color='#900'>
<span class='total_fabi'>0</span>
<input type='hidden' name='total_fabi' id='total_fabi' style='border: none;' size='6' readonly='readonly'>
</font>
</td>";
echo "</tr>";
}
?>
<tr>
<td colspan='4' align='right'>Total Fabrication & Installation</td>
<td align='right'>
<input type='hidden' value='<?php echo $total_non;?>'>
<?php echo $total_non;?>
</td>
</tr>
</tbody>
</table>
.each() function is not working with me. with this kind of code i stated. do you have any other option where i should use keyup or keydown to calculate the total i needed.. Thanks in advance..

id values must be unique on the page, you can't have more than one element with the same id. That's the fundamental problem.
You can change your id values to class values instead.
It's hard to tell exactly what you're trying to do, but if the goal is to update the total_fabi element within the same row each time a req or was_perc element changes:
$(document).ready(function()
{
$('input').keyup(function()
{
// Find the row (if any) containing this input
var $tr = $(this).closest("tr");
// Find the .req, .was_perc, and .total_fabi elements *within* this row
var $req = $tr.find(".req");
var $was_perc = $tr.find(".was_perc");
var $total_fabi = $tr.find(".total_fabi");
// Do the update (probably better to use `text` than `html`)
$total_fabi.text(parseFloat($req.val()) * parseInt($was_perc.val()));
});
});
Re your comment below:
sir how would i get the total computed generated by $total_fabi for my overall total? in php its just like $total += $total_fabi.. How can i do this in jquery?
You can do that with each:
var total = 0;
$(".total_fabi").each(function() {
total += parseFloat($(this).text());
});

First of all you need to know that ID attribute must be unique and you defined same ID many time.
You can use class instead of ID attribute.

Related

Change color of text in row by checkbox in same row in table

I am creating a very simple table having two columns 1.Text 2.Checkbox. i want that whenever i make the checkbox checked corresponding row's text color should be changed. i don't know how to do that.can anyone guide please?
i tried this way but didn't work. here's the code:
<?php
$var=1;
$cbid = "chechbox".$var;
echo"<table>
<tr>
<th>Text</th>
<th>Checkbox</th>
</tr>";
while($var<=3){
echo"
<tr>
<td>
<input type='text' id='$var' value='$var'>
</td>
<td>
<input type='checkbox' id='$cbid' onclick='fun()'>
</td>
</tr>
</table>
<script>
function fun(){
var a = document.getElementById($var);
var b = document.getElemeentById($cbid);
if(b.checked == true){
a.style.color='red';
}
}
</script>
";
$var++;
$cbid = 'chechbox'.$var;
}
?>
i am beginner. i am not even sure if i can make multiple script using while loop.
You can do so:
document.getElementById('check').onchange = function () {
let textVar = document.getElementById('tableText');
if (document.getElementById('check').checked) {
textVar.style.color = 'red';
} else {
textVar.style.color = 'green';
}
}
<table>
<tr>
<th>Text</th>
<th>Checkbox</th>
</tr>
<tr>
<td><input type='checkbox' id='check' value='$var'></td>
<td><input type='text' id='tableText' value='$var'></td>
</tr>
</table>

Generate multiple tables with multiple links in each table (webpage)

I have a webpage which needs to show multiple tables in the same format, but with different numbers inside + generate appropriate links inside many of the table cells.
Design: The webpage will show 1 table for each School subject, and then the cells inside will show how different homeroom classes have been doing under their teachers guidance, using SAT scores, final exams, and attendance rates. The teacher's names and the subject names must link to another page which displays more info about that specific teacher/subject.
I used to use php to generate tables, but seeing as there needs to be links as well inside these table, and very "customized" ones at that, I'm not sure where to start. Each link is totally unique, no complete duplicates. And with say 6 subjects, and 5 teachers, there will be 36 unique links which must be generated.
Currently I have an sql table with: subject, homeroom_teacher, subject_SAT_rslt_change, sat_retake_count, Final_vs_mid, improved_students_count, attendance_rate, missing_student_count
Below, I have put an html example of the type of table I want to generate for a given subject.
<!--subjects: math, science, literature, art, history, physical education-->
<table>
<tr>
<th colspan="7"<a href="allsubjects.php?subject=math" style="color: #ffffff; text-align: center;">Math</b></th> </tr>
<tr id="tr01">
<td><b> Homeroom Teacher </b> </td>
<td><b> Subject SAT result change </b> </td>
<td><b> Retake count</b> </td>
<td><b> Finals vs midterm difference </b></td>
<td><b> Improved students count </b></td>
<td><b> Attendance rates </b></td>
<td><b> Students missing class </b></td>
</tr>
<tr>
<td><a href="xyz.php?subject=math">Mrs. Xyz </td>
<td>-1% </td>
<td>3 </td>
<td>+22% </td>
<td>2 </td>
<td>-2% </td>
<td>5 </td>
</tr>
<tr>
<td><a href="abc.php?subject=math">Mr. Abc </td>
<td>-22% </td>
<td>2 </td>
<td>+1% </td>
<td>3 </td>
<td>-6% </td>
<td>1 </td>
</tr>
<tr>
<td><a href="msa.php?subject=math">Ms. A </td>
<td>-2% </td>
<td>1 </td>
<td>+10% </td>
<td>32 </td>
<td>-2% </td>
<td>0 </td>
</tr>
</table>
php
<?php
$mysqli = new mysqli("localhost","username","password","database");
if($mysqli->connect_errno)
die("Connection failed".$mysqli->connect_error);
$query = "SELECT * FROM `table1` where subject='math';";
$query .= "SELECT * FROM `table1` where subject='literature';";
$query .= "SELECT * FROM `table1` where subject='science';";
if($mysqli->multi_query($query))
{
$i=0;
do{
$result = $mysqli->store_result();
$finfo = $result->fetch_fields();
$title = '';
$table = '';
$i=0;
foreach($finfo as $f)
{
if($i!=0)
$table = $table. "<th>".$f->name."</th>";
$i++;
}
$table = $table. "</tr>";
while($row = $result->fetch_assoc())
{
$table = $table. "<tr>";
$j=0;
foreach($row as $v)
{
if($j==0) {
$title=$v;
} else {
$table = $table. "<td>".$v."</td>";
}
$j++;
}
$table = $table. "</tr>";
}
echo "<table>";
echo "<tr><th><b>".$title."</b></th></tr>";
echo $table;
echo "</table>";
}while($mysqli->more_results() && $mysqli->next_result());
}
?>
SQL:
insert into table1('math','mrs.xyz','-1%',3,'+22%',2,'-2%',5);
I have tagged javascript and php as I need to use them, but if you know of solutions in other languages you are also welcome to post them.
use " double quote and single quote properly that's all,
$finfo = $result->fetch_fields(); *///example variable*
echo "<a hrea='".$finfo.".php'>Link text </a> ";
another way :
Link text

Trying to Add Row dynamically but getting error

I'm trying to add row consist of three textbox dynamically on click of button with id=btnASize and on click of button with id=btnASizeR want to add a row consist of four textboxes. and on click of button with id=btnWdDelete want to delete the last row which is generated with textboxes and so on.
The three buttons which is mentioned above are generated dynamically and rows with textboxes which will be generated below existing rows are also created on click of those dynamic buttons.Any idea would be appreciated Refer image
$("#btnASize").click(function () {
AddRow($("#SizeR").val(), $("#TolMin").val(), $("#TolMax").val());
$("#SizeR").val("");
$("#TolMin").val("");
$("#TolMax").val("");
});
function insertRow(){}
function AddRow(SizeRange, Tolerancemin,Tolerancemax) {
//Get the reference of the Table's thead element.
var tBody = $("#WireDimTbl > thead> tr")[0];
//Add Row.
row = tBody.insertRow(-1);
//Add Size cell.
var cell = $(row.insertCell(-1));
cell.html(SizeR);
//Add TolMin cell.
cell = $(row.insertCell(-1));
cell.html(TolMin);
//Add TolMax cell.
cell = $(row.insertCell(-1));
cell.html(TolMax);
}
$("#btnWdDelete").click(function () {
var row = $("#SizeR").closest("tr");
//Get the reference of the Table.
var table = $("#WireDimTbl")[1];
//Delete the Table row using it's Index.
table.deleteRow(row[1].rowIndex);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td class='text-left'><strong>Standard Sizes & Tolerances</strong></td>
<td>
<input type='button' ID='btnASize' value='AddSize' />
<input type='button' ID='btnASizeR' value='AddSizeRange' />
<input type='button' ID='btnWdDelete' value='Delete' />
<table ID='WireDimTbl' class='table table-bordered'>
<thead>
<tr>
<th class='text-center'>Size Range (mm)</th>
<th class='text-center'>Tolerance (-)mm</th>
<th class='text-center'>Tolerance (+) mm</th>
</tr>
</thead>
<tr>
<td class='text-center'>
<input type='text' ID='SizeR' value='2.00' />
</td>
<td>
<input type='text' ID='TolMin' value='1' />
</td>
<td>
<input type='text' ID='TolMax' value='1' />
</td>
</tr>
</table>
</td>
</tr>
I prepared this sample to fulfill your requirement, although not a complete solution. You have to write some code by yourself. But this will give you a pretty good idea.
$('#btnAdd').click(function() {
var textboxSize = "<input class='form-control' type='text' class='size range'>";
var textboxTolerance = "<input class='form-control' type='text' class='tolerance'>";
var markup = "<tr><td>" + textboxSize + "</td><td>" + textboxTolerance + "</td></tr>";
$("#myTable tbody").append(markup);
});
$('#btnDelete').click(function() {
$("#myTable tbody>tr:last").remove();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<input class="btn-primary" id="btnAdd" type="button" value="Add Row">
<input class="btn-primary" id="btnDelete" type="button" value="Delete">
<table class="table" id="myTable">
<thead>
<th>
Size Range
</th>
<th>
Tolerance
</th>
</thead>
<tbody>
</tbody>
</table>
I think there are a few issues with your code.
You call insertRow on an HTMLTableRowElement. insertRow is a HTMLTableElement method, so we need to make sure we're calling it on a HTMLTableElement, instead of a HTMLTableRowElement. To fix this, we'll select the table. We can then use insertRow() on it.
You call $(row.insertCell(-1)) to insert a cell. This is invalid jQuery code. insertCell is a plain JS method for a HTMLTableRowElements, so we need to make sure we're calling it on the appropriate type of element. Specifically, we'll use row.insertCell(), instead of $(row.insertCell(-1)).
The Delete function contains similar errors, but I'll leave that one as is so you can learn by correcting it yourself.
$("#btnASize").click(function() {
AddRow($("#SizeR").val(), $("#TolMin").val(), $("#TolMax").val());
$("#SizeR").val("");
$("#TolMin").val("");
$("#TolMax").val("");
});
function AddRow(SizeRange, Tolerancemin, Tolerancemax) {
//Get the reference of the Table's thead element.
var tBody = $("#WireDimTbl")[0];
//Add Row.
row = tBody.insertRow(-1);
//Add Size cell.
var cell1 = row.insertCell(-1);
$(cell1).text(SizeRange);
//Add TolMin cell.
var cell2 = row.insertCell(-1);
$(cell2).text(Tolerancemin);
//Add TolMax cell.
var cell3 = row.insertCell(-1);
$(cell3).text(Tolerancemax);
}
$("#btnWdDelete").click(function() {
var row = $("#SizeR").closest("tr");
//Get the reference of the Table.
var table = $("#WireDimTbl")[1];
//Delete the Table row using it's Index.
table.deleteRow(row[1].rowIndex);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td class='text-left'><strong>Standard Sizes & Tolerances</strong></td>
<td><input type='button' ID='btnASize' value='AddSize' /><input type='button' ID='btnASizeR' value='AddSizeRange' /><input type='button' ID='btnWdDelete' value='Delete' />
<table id='WireDimTbl' class='table table-bordered'>
<thead>
<tr>
<th class='text-center'>Size Range (mm)</th>
<th class='text-center'>Tolerance (-)mm</th>
<th class='text-center'>Tolerance (+) mm</th>
</tr>
</thead>
<tr>
<td class='text-center'><input type='text' ID='SizeR' value='2.00' /></td>
<td><input type='text' ID='TolMin' value='1' /></td>
<td><input type='text' ID='TolMax' value='1' /></td>
</tr>
</table>
</td>
</tr>

How To Get Hidden TD Value when i click on a TR

im trying to make a task manger based on web system that can monitor tasks at work , im using html and php .
im trying to show all the tasks in table and when i click on a task (row) i want to get a hidden td value (id of task) and send it as arg to another page for more information about the task .
i searched the web how can i do that , but i didnt realy understand how to do it with my table .
here is my table code
<table id="thickets_show">
<tr id="show_ticket_table_header">
<td>Work Week</td>
<td>Task Submited Date</td>
<td>Task Submited Time</td>
<td>Task</td>
<td>Project</td>
<td>Task Owner</td>
<td>Task Assigend to</td>
<td>Priority</td>
<td>Status</td>
<td>Task Total Work Time</td>
<td>Task Due Date</td>
<td>Task Finish Date</td>
<td>Team</td>
</tr>';
foreach ($tasks as $key => $value) {
if ($value['ticket_status']=="done")
echo '<tr id="done_ticket" >';
elseif ($value['ticket_priority']=="high")
echo '<tr id="high_ticket" class="ticket_raw">';
else
echo '<tr class="ticket_raw">';
echo '
<td>
'.$value['work_week'].'
</td>
<td>
'.$value['ticket_date'].'
</td>
<td>
'.$value['ticket_time_submit'].'
</td>
<td>
'.$value['ticket_request'].'
</td>
<td>
'.$value['ticket_project'].'
</td>
<td>
'.$value['ticket_onwer'].'
</td>
<td>
'.$value['ticket_assigned_user'].'
</td>
<td>
'.$value['ticket_priority'].'
</td>
<td>
'.$value['ticket_status'].'
</td>
<td>
'.$value['ticket_worktime'].'
</td>
<td>
'.$value['ticket_due_date'].'
</td>
<td>
'.$value['ticket_finish_date'].'
</td>
<td>
'.$value['team'].'
</td>
<td style="display:none;" id="ticket_id class="divOne">
'.$value['id'].'
</td>
</tr>
this is the function that im using
$(function(){
$(".ticket_raw" ).on(\'click\',function(e){
e.preventDefault();
var id = $(this).attr("#ticket_id");
alert(id);
});
});
There is a small issue to correct, then you can make this work nice and easily:
echo '<tr id="done_ticket" >'; is invalid - if you're creating multiple elements in a loop like this, you can't give them all the same "id", that's illegal in the HTML specification. You have to use classes instead.
Rewrite it slightly like this:
foreach ($tasks as $key => $value) {
echo '<tr data-id="'.$value['id'].'" class="ticket ';
if ($value['ticket_status']=="done")
echo 'done_ticket';
elseif ($value['ticket_priority']=="high")
echo 'high_ticket ticket_raw';
else
echo 'ticket_raw';
echo '">';
echo '
<td>
//etc...
Note the extra class "ticket" on the tr element, regardless of the status, and the "data-id" attribute containing the ID (instead of a hidden field).
Now, you can write some jQuery to get the ticket ID:
$(".ticket").click(function(event) {
var id = $(this).data("id"); //gets the data-id value from the clicked tr
window.location.href = "ticket.php?id=" + id; //example URL to redirect to, passing the ID from the tr
});
Lastly you can delete this code:
<td style="display:none;" id="ticket_id class="divOne">
'.$value['id'].'
</td>
The td has the id ticket_id, so you can use document.getElementById():
var td = document.getElementById('ticket_id');
var value = td.textContent;
Or, using jQuery:
var td = $('#ticket_id');
var value = td.text();
$('tr').on('click',function(){
var hidden_items = $(this).find('.td_hidden');
$.each(hidden_items,function(k,v){
console.log($(v).text());
})
})
html,body{
height: 100%;
margin: 0 auto;
padding: 0px;
}
td{
border:1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<body>
<table>
<tr>
<td>COLUMN1</td>
<td>COLUMN2</td>
<td>COLUMN3</td>
<td>COLUMN4</td>
</tr>
<tr>
<td>VALUE01</td>
<td>VALUE02</td>
<td>VALUE03</td>
<td>VALUE04</td>
<td style="display:none;" class="td_hidden">VALUE_HIDDEN_01</td>
<td style="display:none;" class="td_hidden">VALUE_HIDDEN_02</td>
</tr>
<tr>
<td>VALUE11</td>
<td>VALUE12</td>
<td>VALUE13</td>
<td>VALUE14</td>
<td style="display:none;" class="td_hidden">VALUE_HIDDEN_11</td>
<td style="display:none;" class="td_hidden">VALUE_HIDDEN_12</td>
</tr>
</table>
</body>

get detail value from database on <tr> hover

Hello guys i have a problem which i can't figure out for a little while. i have a loop which return value from database and i want each value to view their value on onmouseover property of JavaScript. but it only shows the first row value for all the tags. here is the php part of code
$result = "<table id='displayDiv' width='1000' class='table_info table-bordered table-striped table-hover'>
<tr>
<td colspan='6' class='plate'>Follow-Up Events</td>
</tr>
<tr style='text-align:center; color:#FFF; background: #31B0D5;'>
<td>Customer</td>
<td>Plate</td>
<td class='col-md-4'>Problem</td>
<td>Date Created</td>
<td></td>
</tr>";
foreach ($followArray as $customer) {
$result = $result .
"<tr style='text-align:center; background: #FFF; color:#105a99; font-weight:bold;'>
<td>$customer->company</td>
<td id='plate' onmouseover='plate();' onmouseout='plateout();'>$customer->plate</td>
<td>$customer->problem</td>
<td>$customer->date</td>
</tr>";
}
$result = $result . "</table><div id'white'></div>";
and the javascript
function plate() {
document.getElementById("white").innerHTML = $("#plate").text();
}
function plateout() {
document.getElementById("white").innerHTML = "";
}
Thanks for the help.
As you are using native js, just pass this into your plate function and use this.innerHTML.
Also fix the html - ids should be unique so either change it to a class or append a unique number onto the end (in the example below I have changed it to a class) - you should never have an id in a loop (unless you are appending an index or something like that).
And there should be an = in the white div
function plate(columnCell) {
document.getElementById('white').innerHTML = columnCell.innerHTML;
}
function plateout() {
document.getElementById('white').innerHTML = '';
}
<table id='displayDiv' width='1000' class='table_info table-bordered table-striped table-hover'>
<tr>
<td colspan='6' class='plate'>Follow-Up Events</td>
</tr>
<tr style='text-align:center; color:#FFF; background: #31B0D5;'>
<td>Customer</td>
<td>Plate</td>
<td class='col-md-4'>Problem</td>
<td>Date Created</td>
<td></td>
</tr>
<tr style='text-align:center; background: #FFF; color:#105a99; font-weight:bold;'>
<td>$customer->company</td>
<td class='plate' onmouseover='plate(this);' onmouseout='plateout(this);'>$customer->plate</td>
<td>$customer->problem</td>
<td>$customer->date</td>
</tr>
<tr style='text-align:center; background: #FFF; color:#105a99; font-weight:bold;'>
<td>$customer->company</td>
<td class='plate' onmouseover='plate(this);' onmouseout='plateout();'>$customer->plate1</td>
<td>$customer->problem</td>
<td>$customer->date</td>
</tr>
<tr style='text-align:center; background: #FFF; color:#105a99; font-weight:bold;'>
<td>$customer->company</td>
<td class='plate' onmouseover='plate(this);' onmouseout='plateout(this);'>$customer->plate2</td>
<td>$customer->problem</td>
<td>$customer->date</td>
</tr>
</table>
<div id="white"></div>
If you want a jQuery solution then using the new class of plate (and removing the onmouseover and onmouseout from the html) you can do something like this:
// run in your document ready
var white = $('#white');
$('.plate').hover(
function() {
// mouseover
white.text($(this).text());
}, function() {
// mouseoout
white.text('');
}
);

Categories

Resources