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

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

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>

how to export html table to excel, with pagination

I have a form which displays mysql data in the form of an HTML table, using pagination of 5 records per page. I'm trying to export my table to excel, but it's only exporting data of the rows that are currently show, meaning if there are 20 rows, it only shows the first 5 as those get displayed. How can I make it export the one's that are not being displayed but still part of the search? I saw a few other people with a similar question but none have answers( How to export all HTML table rows to Excel file from a paginated table?). Hopefully I can get one!
<?php
if(isset($_GET['submit']) || isset($_GET['page'])){
// Setting up the Pagination below
echo '<center>';
$page_query = "SELECT * FROM tbl_call_log_detail ";
$page_query .= "WHERE
(dealer_id = '$call_id' AND '$endDate'='1970-01-01' AND '$startDate' ='1970-01-01')
OR ( Time <= '$endDate' AND Time >= '$startDate'
AND (dealer_id = '$call_id' OR'$call_id'='' ))
OR ('$endDate'='1970-01-01' AND '$startDate' ='1970-01-01' AND '$call_id'='') ";
$page_result = mysqli_query($conn, $page_query);
$total_records = mysqli_num_rows($page_result);
$total_pages = ceil($total_records/$record_per_page);
$start_loop = $page;
$difference = $total_pages - $page;
if($difference <= $total_pages){
$start_loop = $total_pages - $difference;
}
$end_loop = $start_loop + 2;
if($end_loop > $total_pages){
$end_loop = $total_pages;
}
if($difference > $total_pages){
$end_loop = $total_pages;
}
echo '<div class = "center">';
echo '<div class = "pagination">';
if($page > 1){
echo "<a href= 'dealer_call_log.php?page=1".$urlparameter."'>First</a>";
echo "<a href= 'dealer_call_log.php?page=".($page - 1).$urlparameter."'> << </a>";
}
for ($i = $start_loop; $i <= $end_loop; $i++){
echo "<a href= 'dealer_call_log.php?page=".$i.$urlparameter."'>".$i."</a>";
}
if($page < $end_loop){
echo "<a href= 'dealer_call_log.php?page=".($page + 1).$urlparameter."'> >> </a>";
echo "<a href= 'dealer_call_log.php?page=".$total_pages.$urlparameter."'>Last</a>";
}
if($page < 1){
$page = 1;
}
echo '</div>';
echo '</div>';
echo '<br>';
$sql = "SELECT Name, SFID, Comment, Time FROM tbl_call_log_detail
WHERE
(dealer_id = '$call_id' AND '$endDate'='1970-01-01' AND '$startDate' ='1970-01-01')
OR ( Time <= '$endDate' AND Time >= '$startDate'
AND (dealer_id = '$call_id' OR'$call_id'='' ))
OR ('$endDate'='1970-01-01' AND '$startDate' ='1970-01-01' AND '$call_id'='')
ORDER BY Time DESC LIMIT $start_from, $record_per_page ";
$result = mysqli_query($conn, $sql);
$row = mysqli_num_rows($result);
$all_property = array();
echo "<table class = 'data-table' border = '1' cellpadding = '9' bgcolor = '#CCCCCC' id = 'data-table'>
<tr class = 'data-heading'>";
while($property = mysqli_fetch_field($result)){
echo '<td><b> '. $property ->name. ' </b></td>';
array_push($all_property, $property ->name);
}
echo '</tr>';
while ($row = mysqli_fetch_array($result)){
echo '<tr>';
foreach($all_property as $item){
echo '<td> '. $row[$item] . ' </td>';
}
echo '</tr>';
echo '</center>';
}
echo '</table>';
echo '<br>';
?>
// This is what is getting the current rows, but not all
<input type = "submit" onclick = "window.open('data:application/vnd.ms-excel, '+encodeURIComponent(document.getElementById('data-table').outerHTML));" value = "Export into excel" />
<?php
}
?>
UPDATE: Found the answer I was looking for I simply ran a new sql query without the LIMIT clause and stored it in a hidden table. I then use the hidden table to export data
// SQL and hidden table for exporting to excel
$page_query2 = "SELECT * FROM tbl_call_log_detail ";
$page_query2 .= "WHERE
(dealer_id = '$call_id' AND '$endDate'='1970-01-01' AND '$startDate' ='1970-01-01')
OR ( Time <= '$endDate' AND Time >= '$startDate'
AND (dealer_id = '$call_id' OR'$call_id'='' ))
OR ('$endDate'='1970-01-01' AND '$startDate' ='1970-01-01' AND '$call_id'='') ORDER BY TIME DESC ";
$page_result2 = mysqli_query($conn, $page_query2);
$row2 = mysqli_num_rows($page_result2);
$all_property2 = array();
echo "<table class = 'data-table2' border = '1' cellpadding = '9' bgcolor = '#CCCCCC' id = 'data-table2' hidden>
<tr class = 'data-heading2'>";
while($property = mysqli_fetch_field($page_result2)){
echo '<td><b> '. $property ->name. ' </b></td>';
array_push($all_property2, $property ->name);
}
echo '</tr>';
while ($row2 = mysqli_fetch_array($page_result2)){
echo '<tr>';
foreach($all_property2 as $item){
echo '<td> '. $row2[$item] . ' </td>';
}
echo '</tr>';
echo '</center>';
}
echo '</table>';
?>
<input type = "submit" onclick = "window.open('data:application/vnd.ms-excel, '+encodeURIComponent(document.getElementById('data-table2').outerHTML));" value = "Export into excel" />
<?php
}
?>
You can use JQuery table2excel plugin following is the link
http://www.jqueryscript.net/table/Export-Html-Table-To-Excel-Spreadsheet-using-jQuery-table2excel.html
Try following code pen to only JavaScript
https://codepen.io/kostas-krevatas/pen/mJyBwp

How to put validation on a dynamic dropdown when inserting in PHP?

I'm constructing a survey and I have a textbox that generates dynamic dropdowns based on user input which displays the same data.
This is the script
<script>
function load_questions(){
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax.php??main=1&subcategory="+document.getElementById("subcategorydd").value +"&cnt="+document.getElementById("q_num").value,false);
xmlhttp.send(null);
document.getElementById("question").innerHTML=xmlhttp.responseText;
}
function checkValues() {
_values = [];
$('.form-control-static').each(function() {
_values.push($(this).val());
//console.log($(this).val());
});
sameValue = false;
for ($i = 0; $i < (_values).length; $i++) {
for ($w = 0; $w < (_values).length; $w++) {
if (_values[$i] === _values[$w] && $i != $w) {
sameValue = true;
}
}
}
if (sameValue) {
alert('has the same value .');
return false;
}
alert('there is no the same value');
//do something .
}
</script>
This is the insert code when I'm creating the survey
<?php
$con = mysqli_connect("localhost","root","","imetrics");
if(isset($_POST['submit'])){
$title = $_POST['surveytitle'];
$catdd = $_POST['catdd'];
$subcatdd = $_POST['subcatdd'];
$gender = $_POST['gender'];
$age = $_POST['age'];
$occupation = $_POST['occupation'];
$occupationtwo = $_POST['occupdd'];
$relstatus = $_POST['relationshipstatus'];
$q_num = $_POST['q_num'];
$insert = mysqli_query($con, "INSERT INTO `surveyform` (`surveytitle`,`surveycategory`,`surveysubcategory`,`gender`,`age`,`occupation`,`occupation_status`,`status`) VALUES ('$title','$catdd','$subcatdd','$gender','$age','$occupation','$occupationtwo','$relstatus')");
if(!$insert){
echo mysqli_errno();
}
else{
$getMaxID = mysqli_query($con, "SELECT MAX(survey_id) as maxid FROM surveyform");
$row_2 = mysqli_fetch_array($getMaxID);
$survey_id = $row_2[0];
for( $a = 1; $a <= $q_num; $a++)
{
mysqli_query($con, "INSERT INTO surveyform_questions ( survey_id, question_id) VALUES ('$survey_id', ". $_POST['question_dropdowns'.$a] .")");
//echo "INSERT INTO surveyform_questions ( survey_id, question_id) VALUES ('$survey_id', ". $_POST['question_dropdowns'.$a] .")";
}
echo '<script language="javascript">';
echo 'alert("Survey Created!")';
echo '</script>';
}
}
?>
And this is my dropdown code
if($question !="" && $cnt!="" && $addQues!="yes" && $main != 1){
$i = 0;
for ($i = 1; $i <= $cnt; $i++)
{
$query=mysqli_query($con, "SELECT * FROM question WHERE question_subcat = $question ");
echo "<b>Question #". $i."</b>";
echo "<select id='question_dropdown".$i."' class='form-control-static' name='question_dropdowns".$i."'>";
echo "<option selected>"; echo "Select"; echo "</option>";
while($row=mysqli_fetch_array($query))
{
echo "<option value='$row[question_id]'>";
echo $row["questiontitle"];
echo "</option>";
}
echo "</select>";
echo "<br />";
}
echo "<div id='insertQuesHere".$i."'></div>";
echo "<a href='#add_question' onclick='return addQues();'>Add Question</a>";
}
here's my submit button
<input type="submit" name="" id="btnSaveSurvey" class="form-control-static" onclick="checkValues();" value="check" />
What's the validation code that will prevent me from inserting if the data chosen from the dropdown is the same? For example I generated 2 dropdowns and I chose the same datas from the dropdown, what's the validation code for it?
Please call checkValues method your submit button click
<input type="submit" name="" id="btnSaveSurvey" class="form-control-static" onclick="checkValues();" value="check" />
checkValues method below :
function checkValues() {
_values = [];
$('.form-control-static').each(function() {
_values.push($(this).val());
//console.log($(this).val());
});
sameValue = false;
for ($i = 0; $i < (_values).length; $i++) {
for ($w = 0; $w < (_values).length; $w++) {
if (_values[$i] === _values[$w] && $i != $w) {
sameValue = true;
}
}
}
if (sameValue) {
alert('has the same value .');
return false;
}
alert('there is no the same value');
//do something .
}
Also , you can see an example Example

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?

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