Javascript - perform operation vertically and horizontally with dynamic text input - javascript

need help i am working with some text inputs here that are dynamic depending on how many the user enter. what i wanted to do is to compute the text inputs automatically after user input value using onkeyup javascript.
here the php and html code:
<?Php
$x = 10;
$i = 0;
for($i=0; $i<$x; $i++){
echo "<input type='text' onkeyup='multiply()' id='tb1'>";
echo "x";
echo "<input type='text' onkeyup='multiply()' id='tb2'>";
echo "=";
echo "<input type='text' onkeyup='multiply()' id='tb3'>";
echo "<br>";
}
?>
total:<input type='text' onkeyup='multiply()' id='tb4'>
and here's the javascript:
<script>
function multiply(){
var textbox1 = document.getElementById('tb1').value;
var textbox2 = document.getElementById('tb2').value;
var result = parseFloat(textbox1) * parseFloat(textbox2);
if(!isNaN(result))
{
document.getElementById('tb3').value = result;
}
}
</script>
now, the first row of text inputs works fine but the remaining text inputs doesn't I know i'm missing something here and i can't figure it out, how can
i compute horizontally those values from tb1 and tb2 then display it on tb3
and compute vertically all the values of tb3 and display it in tb4. any help is much appreciated.TIA

Well all rows contain elements with same ids. So row 1 will contain elements with ids: tb1, tb2, tb3. Row 2 will also contain elements with ids tb1, tb2 and tb3.
The id of each element on a page needs to be unique. You can make the ids unique by appending the row number to the id. For example:
<?php
$x = 10;
$i = 0;
for($i=0; $i<$x; $i++){
echo "<input type='text' onkeyup='multiply(" . $i . ")' id='tb" . $i . "-1'>";
echo "x";
echo "<input type='text' onkeyup='multiply(" . $i . ")' id='tb" . $i . "-2'>";
echo "=";
echo "<input type='text' onkeyup='multiply(" . $i . ")' id='tb" . $i . "-3'>";
echo "<br>";
}
?>
Total: <input type='text' id='tb4'> <input type='button' onclick='CalculateSum()' title='Calculate Sum'>
Your JavaScript code will then look as follows:
<script>
function multiply(row) {
var textbox1 = document.getElementById('tb' + row + '-1').value;
var textbox2 = document.getElementById('tb' + row + '-2').value;
var result = parseFloat(textbox1) * parseFloat(textbox2);
if(!isNaN(result))
{
document.getElementById('tb' + row + '-3').value = result;
}
}
function CalculateSum() {
let total = 0;
for (let i=0; i < 10; i++) {
total += document.getElementById('tb' + i + '-3').value;
}
document.getElementById('tb4').value = total;
}
</script>

Related

Star rating system created through loop

enter image description hereI have a table that displays a list of recipes from a database. Each recipe stores a rating out of 5. If no ratings has been submitted 'Not yet rated' will display. If a recipe has a rating, for example, 3, I would like 3 stars to appear. I have wrote jquery to try to achieve this but it works for the first recipe and not for the rest. For each recipe, more stars are printed. Any ideas where I'm going wrong?
if ($avg !=0)
{
define('RATE_RECIPE_MAX_STAR_RATING', 5);
$contentitems1 = "<form><div class='stars'>";
for ($i = 1; $i <= RATE_RECIPE_MAX_STAR_RATING; $i++)
{
//$contentitems1 .= '<input type="radio" style= "display:none;"
//$contentitems1 .= '<img class="rate_recipe_star" name="star_' . $i . '" id="star_' . $i . '" src="fadedstar.png" width="25" />';
$contentitems1 .= '<span class="fa fa-star-o star" name="star_' . $i . '" id="star_' . $i . '"></span>';
}
"</div></form>";
echo $contentitems1 .="<script type='text/javascript'> paint_the_stars($avg)
</script>";}
echo '<div class="star_' . $avg . '"></div>'?>
function paint_the_stars(howmany) {
var items = new Array();
$(".star").each(function() {
//var star = jQuery(this)
var star = $(this);
console.log(star);
var starno = $(star).attr('id').substring(5);
console.log(starno);
//console.log("Star:"+star);
if (starno <= howmany) {
//console.log("TRUE PRINT A STAR"+starno);
//$(this).attr('src', 'yellowstar.png');
var item = $(this).removeClass("fa-star-o").addClass("fa-star");
items.push(item);
} else {
//return true;
var item = $(this).removeClass("fa-star").addClass("fa-star-o");
items.push(item);
}
if (starno == 5) {
$.each(items, function(){
console.log(this);
$('.star_'+howmany).append(this);
});
return false;
}
})
}

javascript only executing on first row of table

I've got a table row that is repeating 15 times. Then on one of the fields it executes JS. The problem is it's only executing the JS on the first row of the table. What am I doing wrong?
PHP Table script:
for ($x = 1; $x <= 15; $x++) {
echo '<tr>';
echo '<td><input size="6" id="qty" name="qty' . $x . '" type="text"/></td>';
echo '<td><input onfocus="calcTotal()" type="text" name="tot' . $x . '" id="tot" size="6" readonly/></td>';
echo '</tr>';
}
The JS:
function calcTotal() {
var myqty = document.getElementById('qty').value;
var myrate = <?php echo json_encode($therate); ?>;
myResult = myqty * myrate;
var elem = document.getElementById("tot");
elem.value = myResult;
}
Because you are repeating the INPUT, whose ID is qty. You can't repeat DOM IDs, otherwise you run into problems like this.

How to hide a column in sql generated table? (php+jquery)

Looked through various solutions but unable to resolve. So far what I have implemented, only the first row is getting hid whereas the id of column remains same throughout. Can you please tell me that what needs to be changed?
JAVASCRIPT:
<script>
$(document).on("pagecreate","#pageone",function(){
$("button").click(function(){
var theID = $(this).attr('id');
$("#"+theID).slideToggle("slow");
$("table, tr,th#"+theID).slideToggle("slow");
$("table, tr,td#"+theID).slideToggle("slow");
});
/*
$("button").click(function(){
var theID = $(this).attr('id');
$("#"+theID).slideDown("slow");
$("td.#"+theID).slideDown("slow");
});
*/
});
</script>
The table query
$query = "select * from $table_select";
$result = mysql_query($query);
echo "<table id = 'table-1'>";
$num_columns = mysql_num_fields($result);
echo "<tr>";
for ($i = 0; $i < $num_columns; $i++)
{
echo "<th id='".$i."'>";
$meta = mysql_field_name($result, $i);
if($i == 0) {
$arg1 = $meta;
}
$field_name[] = $meta;
echo "$meta</th>";
}
$k = 0;
while($table = mysql_fetch_array($result)) {
$v[] = $table[0];
echo "<tr class = 'hid_tr'>";
for ($i = 0; $i < $num_columns; $i++) {
echo "<td id='".$field_name[$i]."'>{$table[$i]}</td>";
if($i == $num_columns-1) {
echo '<td><form action="'.$_SERVER['PHP_SELF'].'" method="post"> <input type="hidden" id="quoteid" name="quoteid" value='.$v[$k].' /><input type="hidden" id="db" name="db" value='.$db_select.' /> <input type="hidden" id="table" name="t" value='.$table_select.' /> <input type="hidden" id="field" name="field" value='.$arg1.' /> <input type="submit" name="formDelete" id"formDelete" value="" style="background-color:#f00;color:#fff;"/></form></td>';
}
}
echo "</tr>";
$k += 1;
}
echo '<tr>';
for ($i = 0; $i < $num_columns; $i++) {
//echo 'Slide up';
echo '<td><button id="'.$field_name[$i].'">Toggle '.$field_name[$i].'</button></td>';
}
echo '</tr>';
/*
echo '<tr>';
for ($i = 0; $i < $num_columns; $i++) {
//echo 'Slide Down';
echo '<td><button id="'.$field_name[$i].'">Slide down</button></td>';
}
echo '</tr>';
*/
echo "</table>";
The toggle button
echo '<tr>';
for ($i = 0; $i < $num_columns; $i++) {
//echo 'Slide up';
echo '<td><button id="'.$field_name[$i].'">Toggle '.$field_name[$i].'</button></td>';
}
echo '</tr>';
Thanks!
If what you mean is you want all the rows' 3rd tds to be hidden when someone clicks the button in the 3rd td of the top row, then you need to do something like this:
CREATING THE HEADERS
echo '<tr>';
for ($i = 0; $i < $num_columns; $i++) {
//The button calls a function with the proper position
echo '<td id="hideableHeader' . $i . '"><button onclick="hide(' . $i . ');">Toggle '.$field_name[$i].' </button></td>';
}
echo '</tr>';
CREATING THE COLUMNS WITH DATA
Here, you give each TD an id that combines its row and column index like this:
'<td id="hideable_' . $rowNum . '_' . $colNum . '">datahere</td>';
And keep track of total rows.
HIDING (this is a javascript function)
function hide(colNum)
{
//This is the header which will store its state for toggling
var header = document.getElementById( "hideableHeader" + colNum );
//Hide all of these tds starting after the first header row
for ( var row = 0; row < totalRows; row++ )
{
for ( var col = 0; col < totalCols; col++ )
{
var column = document.getElementById( "hideable_" + row + "_" + col );
//Is hidden, show it
if ( header.isHidden === true ) column.style.visibility = "visible";
//Hide it
else column.style.visibility = "hidden";
}
}
}

Grab two values in loop, check box and variable. Only grabbing checkbox? php w screenshot

i make a sql query asking for data(its a text question), i output the (question) with a checkbox to the left of it and an input field underneath it to give point worth to it(like a teacher making an exam) . All in a loop w arrays. It outputs the correctly checked questions but only will assign point values to first three questions if there checked. so if i check q1 q2 and q4 it will output q1 q2 q4 and q1 points q2points. Thats my problem, I only want to be able to select three total questions and assign those questions their points.
php in the html
$sql = " SELECT Question FROM examQuestions";
$result = mysqli_query($dbCon, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<input type="checkbox" name="checkboxvar[]" value="'.$row["Question"].'">'.$row["Question"].'<input placeholder="10" class="form-control" type="number" name="points[]">'."<br />";
}
}
im trying to output the data using this:
$checkboxvar = $_POST['checkboxvar'];
$examName = $_POST['examName'];
$questionWorth = $_POST['points'];
$i=1;
$total = 0;
while ($i < 4) {
$x = $i - 1;
echo $checkboxvar[$x];
echo $questionWorth[$x]."<br />";
$total = $total + $questionWorth[$x];
$i = $i +1;
}
echo $total;
As I told you in the comments try modifying your code like this:
$sql = " SELECT Question FROM examQuestions";
$result = mysqli_query($dbCon, $sql);
$i = 0;
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo '<input type="checkbox" name="checkboxvar[]" value="'.$i++.'-'.$row["Question"].'">'.$row["Question"].'<input placeholder="10" class="form-control" type="number" name="points[]">'."<br />";
}
}
And then, to have the right points for the correspondig question something like this:
$checkboxvar = $_POST['checkboxvar'];
$examName = $_POST['examName'];
$questionWorth = $_POST['points'];
$i = 0;
$total = 0;
while ($i < 3) {
$question = explode("-", $checkboxvar[$i]);
echo $question[1];
echo $questionWorth[$question[0]]."<br />";
$total += $questionWorth[$question[0]];
$i++;
}
echo $total;
This should do the work.
If i understand your implied question correctly, you will need some client side (javascript) code that keeps track of the number of checked checkboxes. As soon as one checks three boxes all remaining ones and corresponding text boxes are disabled.
for naive vanilla js solution your php could look like this:
$index = 0;
while($row = mysqli_fetch_assoc($result)) {
echo "<label><input class='questions' type='checkbox' name='question_{$index}' value='{$row["Question"]}' on_change='limit_to_three(this);'>{$row["Question"]}<label><br>";
echo "<input class='scores' name='score_{$index}'><br>";
$index++;
}
For modern browsers you would need the following in your javascript :
var selected_count = 0;
function limit_to_three(selected_checkbox) {
if (selected_checkbox.checked) {
selected_count++;
} else {
selected_count--;
}
var limit_reached = (selected_count == 3);
var checkboxes = document.getElementsByClassName('questions');
var scores = document.getElementsByClassName('scores');
for (var i=0; i<checkboxes.length; i++) {
if (!checkboxes[i].checked) {
checkboxes[i].disabled = scores[i].disabled = limit_reached;
}
}
}
Now, upon submit, you can assume that only checked question checkboxes will be submitted, so your php code could be like this:
$total = 0;
$length = strlen('questions_');
foreach ($_POST as $name => $value) {
if (substr($name, 0, $length) == 'questions_') {
$index = substr($name, $length - strlen($name));
echo $_POST[$name];
echo "<br>";
echo $_POST["scores_{$index}"];
$total += $_POST["scores_{$index}"];
}
}
As i said, this is a naive implementation, that sends question texts back and forth. If i were you i would add ID column to your questions table and use it instead of dynamically generated indexes
Then your html could be generated like this:
while($row = mysqli_fetch_assoc($result)) {
echo "<label><input class='questions' type='checkbox' name='question_{$index}' value='{$row["ID"]}' on_change='limit_to_three(this);'>{$row["Question"]}<label><br>";
echo "<input class='scores' name='score_{$row["ID"]}'><br>";
}
and your receiving php could be like this:
$checked = explode(',', $_POST['questions']);
for ($checked as $id) {
$total += $_POST["scores_{$id}"];
}
Also you could retrieve the checked questions by
$sql = "SELECT * FROM Questions WHERE ID IN ({$_POST['questions']})";

get id of a cell in a table inside a div (JS and HTML)

Hi I have a php script that draws a table subject to certain conditions. When the table is drawn it is inside a div called ‘window’ and the table is called ‘visi’ I then want to use the code below to get the id’s of each cell in the table. I can get the class name no problem but get absolutely nothing from the id. Can anyone give me an idea of what i am doing wrong?. I have tried a similar peice of code on a table that is not inside a div and it works fine. Any help would be great and I hope the code makes sense.
function confirm_allocate() {
var msg = ""
var tab = document.getElementById('visi');
var r = tab.rows.length
for (i=0; i<r; i++){
cc = tab.rows.cells.length
for (col=0; col<cc; col++){
x=document.getElementById('visi').rows.cells;
iden = x[col].className
ref = x[col].id
msg += "Class =" + iden + " /// Id =" + ref + "\r"
}
}
alert (msg )
}
If it helps this is the code to draw the table (but this is called using js/ ajax after getting the information for the table )
<?php
$table = "" ;
include '../database_sql/dbconnect.php' ;
include '../functions/job_details.php';
include '../functions/check_date.php';
include '../functions/stock_list.php' ;
include '../functions/allocated_on_date.php' ;
$jobdate = $_GET['jobdate'] ;
$jobnumber = $_GET['jobnumber'] ;
$jobname = $_GET['jobname'] ;
$screens = screens_per_job($jobnumber,$size) ;
$table = "<h2 align= 'center' > $jobname (Job Number $jobnumber) : Screens required : $screens </h2>" ;
$table .= "<table id='visi' width='480px' align='center' cellspacing='1' cellpadding='1' border='1' ><tr>" ;
// get stock list from DB
stock_list() ;
$len = count( $stock);
$evresult = mysql_query("SELECT * FROM event WHERE jobnumber = '$jobnumber' ") ;
$event_row = mysql_fetch_array($evresult);
for ($counter = 0; $counter < $len; $counter++) {
$item = $stock[$counter] ;
$items = $item . "s" ;
$booked_for_job = $event_row[$items] ;
$result = mysql_query("SELECT * FROM $item ") ;
allocated_on_date($jobdate) ; // function
if ($booked_for_job) {
$count = 1 ;
$table .= "<td >$item<br> [$booked_for_job to Allocate] </td> " ;
WHILE ($row = mysql_fetch_array($result)) { ;
$booked_job = $screens[$item][$count]["job"] ; // from the allocated_on_date($jobdate) function
$description = $row['trailer_id'];
$class = $items ;
$id_items = $items . $count ;
$count ++ ;
if ($booked_job == $jobnumber) { // allocated to current job
$table .= "<td class='truckbox' > <div class='$class' id='$id_items' onClick='allocate(\"$booked_for_job\",\"$id_items\")' > " ;
$table .= "$num </div> </td>" ;
} ELSEIF ($booked_job === 0 ) { // available to allocated
$class .= "g" ;
$table .= "<td class='truckbox' > <div class='$class' id='$id_items' onClick='allocate(\"$booked_for_job\",\"$id_items\")' > " ;
$table .= "$num </div> </td>" ;
} ELSE { // allocated to ANOTHER job
$class .= "a" ;
$table .= "<td class='truckbox' > <div class='$class' id='$items' > " ;
$table .= "</td> " ;
}
} // while
$table .= "</tr>" ;
} ; // if
}; //for
$table .= "</table> " ;
$table .= "<table width='200px' align='center' cellspacing='12' cellpadding='1' ><tr>" ; // draw table buttons close and allocate
$table .= "</tr><tr>" ;
$table .= "<td class='truckbox' <div class='yesbutton' id='yes' onClick='confirm_allocate()' ; return false ; > ";
$table .= "<td class='truckbox' <div class='nobutton' id='no' onClick='hide()' > ";
$table .= "</tr></table> ";
echo $table ; // finally draw table
include '../database_sql/dbclose.php' ;
?>
I don't see any id attributes on the table cells (td elements) that are being generated. So ref is just going to be blank or undefined.
If that's not the problem then it could be the .rows.cells. Try .getElementsByTagName('td') instead. I think that line should be outside the loop, since it's not changing on each iteration.
Also, the latter part of your HTML is wrong - you don't close the td tag. Instead of <td class='truckbox' <div class... it should be <td class='truckbox'><div class...
You forgot to access the array elements:
...
for (i=0; i<r; i++) {
var row = tab.rows[i];
var cc = row.cells.length;
for (col=0; col<cc; col++){
var x = row.cells[col];
...

Categories

Resources