javascript only executing on first row of table - javascript

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.

Related

Javascript - perform operation vertically and horizontally with dynamic text input

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>

Update php SQL when checkbox check (no submit button)

I am pulling data out of a database and displaying in a table. I would like my checkbox, when checked/unchecked, to auto-update the value in the database without using a submit button to trigger the action. I'm new to AJAX and tried to adapt some code. I cannot get it to work. One major thing I don't understand is what '#state_span' is for?
Data Page (HTML)
$sql = "SELECT * FROM Orders ORDER BY " .$order;
$myData = mysqli_query($dbconnect, $sql);
while ($record = mysqli_fetch_array($myData)){
if ($record['Sent'] == 0) {
$sent = "";
} else {
$sent = "checked";
}
if ($record['Paid'] == 0) {
$paid = "";
} else {
$paid = "checked";
}
echo "<tr>";
echo '<td class="MenuLeft">' . $count . "</td>";
echo '<td class="MenuMid">' . $record['Name'] . "</td>";
echo '<td class="MenuRight"><input type="checkbox"
name="Sent"
id="'. $record['ID'] .'"
class="ChkSwitch"' . $sent . ' ></td>';
echo '<td class="MenuRight"><input type="checkbox"
name="Paid"
id="'. $record['ID'] .'"
class="ChkSwitch"' . $paid . ' ></td>';
echo "</tr>";
echo '<script>
$(document).ready(function() {
$(".ChkSwitch").click(function() {
var id = this.id;
var col = this.name; //Tell us what column to update
var state = this.checked ? 1 : 0;
$("#state_span").load("ChkUpdate.php?d="+id+"&col="+col+"&state="+state);
}
}
</script>
';
PHP
$id = $_GET['id'];
$state= $_GET['state'];
$col= $_GET['col'];
include("dbconnect.php");
$query = "UPDATE Orders SET '$col' = '$state' WHERE ID = '$id' ";
mysqli_query($dbconnect, $query);

ReferenceError: Function Not Defined. What am I missing?

Can't seem to figure out why I keep getting this ReferenceError: OnLoad is not defined error.
Since the time of my previous commit, I have changed lines 28-30 and that is all.
How can this cause my javascript to not be loaded properly? I have only changed these three lines. I'm certain these lines shouldn't really be related. The Javascript file is identical to the one in the previous commit.
What am I missing?
UserInterface.php - Current Commit
class UserInterface {
var $ParentAppInstance;
function __construct($AppInstance){
$this->ParentAppInstance = $AppInstance;
$this->DrawPageHTML();
$this->DrawDBSetDropdown();
$this->DrawQueryForm();
}
//Override thjis function to change the HTML and PHP of the UI page.
protected function DrawPageHTML(){
$CurrDB_Obj = $this->ParentAppInstance->CurrentDBObj; //Line 28
$EncodedFields = json_encode($CurrDB_Obj->GetFields()); //Line 29
echo "<body onload='OnLoad($EncodedFields);'>"; // Line 30
echo '
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<link rel="stylesheet" type="text/css" href="./CSS/UserInterface.css">
<div id="DebugOutput"></div>
</body>
';
}
protected function DrawDBSetDropdown(){
echo '<div align="right">';
echo '<select onchange="SwitchDatabaseSet();" name="DBSetList" form="DBSetSelector" id="DBSetSelector">';
$i = 0;
foreach ($this->ParentAppInstance->DBSetsArr as $DBSet){
if ($DBSet->DBSetName == $this->ParentAppInstance->CurrDBSetStr){
echo '<option value="' . $DBSet->DBSetName . '">' . $DBSet->DBSetName . '</option>';
}
}
foreach ($this->ParentAppInstance->DBSetsArr as $DBSet){
if ($DBSet->DBSetName == $this->ParentAppInstance->CurrDBSetStr){/* DO NOTHING. IE. IGNORE IT*/}
else if ($DBSet->DBSetName == 'DBSet0'){/* DO NOTHING. IE. IGNORE IT*/}
else{
//Add the DBSet to the dropdown list.
$i++;
echo '<option value="' . $DBSet->DBSetName . '">' . $DBSet->DBSetName . '</option>';
}
}
echo '</select>';
echo '</div>';
}
protected function DrawQueryForm(){
echo '<form action="DatabaseSearch.php" method="post" accept-charset="UTF-8">';
echo '<div id="QFormBody">';
$NumActiveQBoxes = $this->ParentAppInstance->Config['ApplicationSettings']['NumberDefaultQueryOptions'];
for ($i = 1; $i <= $NumActiveQBoxes; $i++){
echo '<div class="QueryBox" name="QBox_' . $i . '">';
echo '<select name=Field_' . $i . '">';
$DBSet_Num = filter_var($this->ParentAppInstance->CurrDBSetStr, FILTER_SANITIZE_NUMBER_INT);
$CurrDBSet_Obj = $this->ParentAppInstance->DBSetsArr[$DBSet_Num];
foreach($CurrDBSet_Obj->GetDBSetFields() as $Field){
//echo $Field;
echo '<option>' . $Field . '</option>';
}
echo '</select>';
echo '<input type="text" name="Query_' . $i . '"></input>';
echo '<button class= "RMButton" type="button">-</button>';
echo '</div>';
}
echo '<button type="button" id="add" onclick="AddQueryBox();">+</button>';
echo '<button type="submit" id="submit">SEARCH</button>';
echo '</Form>';
echo '<script src=/GLS_DBSearchProject/JavaScript/UserInterface.js></script>';
}
UserInterface.php - Previous Commit
class UserInterface {
var $ParentAppInstance;
function __construct($AppInstance){
$this->ParentAppInstance = $AppInstance;
$this->DrawPageHTML();
$this->DrawDBSetDropdown();
$this->DrawQueryForm();
}
//Override thjis function to change the HTML and PHP of the UI page.
protected function DrawPageHTML(){
$DBSet_Num = filter_var($this->ParentAppInstance->CurrDBSetStr, FILTER_SANITIZE_NUMBER_INT); //Line 28
$CurrDBSet_Obj = $this->ParentAppInstance->DBSetsArr[$DBSet_Num]; //Line 29
$EncodedFields = json_encode($CurrDBSet_Obj->GetDBSetFields()); //Line 30
echo "<body onload='OnLoad($EncodedFields);'>";
echo '
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<link rel="stylesheet" type="text/css" href="./CSS/UserInterface.css">
<div id="DebugOutput"></div>
</body>
';
}
protected function DrawDBSetDropdown(){
echo '<div align="right">';
echo '<select onchange="SwitchDatabaseSet();" name="DBSetList" form="DBSetSelector" id="DBSetSelector">';
$i = 0;
foreach ($this->ParentAppInstance->DBSetsArr as $DBSet){
if ($DBSet->DBSetName == $this->ParentAppInstance->CurrDBSetStr){
echo '<option value="' . $DBSet->DBSetName . '">' . $DBSet->DBSetName . '</option>';
}
}
foreach ($this->ParentAppInstance->DBSetsArr as $DBSet){
if ($DBSet->DBSetName == $this->ParentAppInstance->CurrDBSetStr){/* DO NOTHING. IE. IGNORE IT*/}
else if ($DBSet->DBSetName == 'DBSet0'){/* DO NOTHING. IE. IGNORE IT*/}
else{
//Add the DBSet to the dropdown list.
$i++;
echo '<option value="' . $DBSet->DBSetName . '">' . $DBSet->DBSetName . '</option>';
}
}
echo '</select>';
echo '</div>';
}
protected function DrawQueryForm(){
echo '<form action="DatabaseSearch.php" method="post" accept-charset="UTF-8">';
echo '<div id="QFormBody">';
$NumActiveQBoxes = $this->ParentAppInstance->Config['ApplicationSettings']['NumberDefaultQueryOptions'];
for ($i = 1; $i <= $NumActiveQBoxes; $i++){
echo '<div class="QueryBox" name="QBox_' . $i . '">';
echo '<select name=Field_' . $i . '">';
$DBSet_Num = filter_var($this->ParentAppInstance->CurrDBSetStr, FILTER_SANITIZE_NUMBER_INT);
$CurrDBSet_Obj = $this->ParentAppInstance->DBSetsArr[$DBSet_Num];
foreach($CurrDBSet_Obj->GetDBSetFields() as $Field){
//echo $Field;
echo '<option>' . $Field . '</option>';
}
echo '</select>';
echo '<input type="text" name="Query_' . $i . '"></input>';
echo '<button class= "RMButton" type="button">-</button>';
echo '</div>';
}
echo '<button type="button" id="add" onclick="AddQueryBox();">+</button>';
echo '<button type="submit" id="submit">SEARCH</button>';
echo '</Form>';
echo '<script src=/GLS_DBSearchProject/JavaScript/UserInterface.js></script>';
}
UserInterface.js
var DBSetFields = [];
var NumQBoxes = 3;
//window.onload = OnLoad();
function OnLoad(Fields){
console.log("OnLoad called");
CloneDBSetFields(Fields);
var RMNodeList = document.getElementsByClassName('RMButton');
for (var i = 0; i < RMNodeList.length; ++i) {
console.log(RMNodeList[i]);
RMNodeList[i].onclick = RemoveQBox; // Calling myNodeList.item(i) isn't necessary in JavaScript
}
}
function JSTEST(){
window.alert("JS Called Successfully!!");
}
function CloneDBSetFields(Fields){
console.log("CloneDBSetFields");
DBSetFields = Fields;
}
function SwitchDatabaseSet(MainPageDoc){
document.getElementById("DebugOutput").innerHTML = "Test";
window.location.replace('/GLS_DBSearchProject/index.php?DBSet=' + document.getElementById("DBSetSelector").value);
console.log(document.getElementById("DBSetSelector").value);
//console.log(document.)
}
function Fields_FOREACH(ELEMENT, INDEX, ARRAY){
console.log("TEST");
var FieldOption = document.createElement('option');
FieldOption.setAttribute('value', ARRAY[INDEX]);
FieldOption.innerHTML = ARRAY[INDEX];
this.appendChild(FieldOption);
}
function AddQueryBox(){
NumQBoxes += 1;
var NewQBox = document.createElement('div');
NewQBox.setAttribute('class', 'QueryBox');
//Create and fill Field Selector dropdown "select" element
var FieldSelector = document.createElement('select');
FieldSelector.setAttribute('name', 'Field_' + NumQBoxes);
//foreach element in Fields
console.log(DBSetFields);
DBSetFields.forEach(Fields_FOREACH, FieldSelector);
//Create and fill
var QueryText = document.createElement('input');
QueryText.setAttribute('type', 'text');
QueryText.setAttribute('name', 'Query_' + NumQBoxes);
//Create "-" Remove button for removing query lines.
var RemoveButton = document.createElement('button');
RemoveButton.innerHTML = "-";
RemoveButton.setAttribute('type', 'button');
RemoveButton.setAttribute('class', 'RMButton');
RemoveButton.addEventListener("click", RemoveQBox);
//Combine the individual elements into a new query box and insert the new query box into the HTML Document
NewQBox.appendChild(FieldSelector);
NewQBox.appendChild(QueryText);
NewQBox.appendChild(RemoveButton);
document.getElementById("QFormBody").insertBefore(NewQBox, document.getElementById("add"));
}
function RemoveQBox(e){
console.log("Remove");
var RemoveButton = this; //this == e.currentTarget
console.log(RemoveButton);
var QBox = RemoveButton.parentNode;
QBox.remove();
NumQBoxes -= 1;
}
EDIT: My Javascript file is not being loaded on the client side (ie. it doesn't show up under "Sources", so I'm not really not sure: Why wouldn't my javascript be loading on the client side?

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

Categories

Resources