I'm trying to manipulate my HTML table using datavalues from an SQL database that I'm extracting using PHP.
I've tried a tonne of different ways but I think the best way would be how I am approaching it now, by using a loop to assign an ID tag number corresponding to the Matrix Value of that array.
(EXAMPLE: 11, 12, 13, 21, 22, 23 etc..)
I am then calling a JavaScript function to find the element with that particular ID and replace the value with the SQL Data taken out by the PHP code.
I've inspected the elements on Chrome and can see the data going into the function but the values within the table are staying blank and not being set to the values from the mySQL.
Any help or suggestions will be greatly appreciated.
<?php
$sql = "SELECT * FROM `stock` WHERE 1";
$tableHeader = "<body><center><div><table id=\"infoTable\" class=\"myTable \"><tr><th></th><th> 1 </th><th> 2 </th><th> 3 </th></tr>";
$r_query = mysql_query($sql);
//To Table Details
//prints StackerReclaimer_StatusTable;
include("SR_TableStatus.php");
// output data of each row
echo $tableHeader;
for ($i=1;$i<5;$i++){ //Rows
$row = mysql_fetch_array($r_query);
if($i == 2 || $i==4)
echo"<tr><td> </td></tr>";
echo"<tr><td class = \"leftCol\"> Bed ".($i)."</td>";
for ($j=1;$j<4;$j++){ //Cols
echo"<td bgcolor=\"#E9E6E5\" id =\"$i$j\"></td>";
/***************************************/
$data = strtoupper($row["sortcode"])." (".(($row["stock"])/1000)."k)";
if( $row["bednumber"] == $i && $row["pilenumber"] == $j ){
// echo"<td bgcolor=\"#E9E6E5\" id = $i$j>".strtoupper($row["sortcode"])." (".(($row["stock"])/1000)."k)</td>";
echo "<script>swapValue($i$j, ".$data.");</script>";
}
/***************************************/
}
echo"</tr>";
}
echo "</table></div></body></center>";
?>
<!-- This script allows user to click on table rows to direct user to More info for that Coal -->
<script>
function swapValue(var location, var data){
var s = document.getElementById(location);
s.value = data;
}
var table = document.getElementById("infoTable");
if (table != null) {
for (var i = 1; i < table.rows.length; i++) {
for (var j = 1; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
tableText(this);
myFunc();
};
}
}
function tableText(tableCell) {
//alert(tableCell.innerHTML);
var Val = tableCell.innerHTML;
Val = Val.substring(0,7);
document.getElementById("searchBox").value = Val;
document.getElementById("searchButton").click();
}
</script>
echo "</table></div></body></center>"
first you did not end the tag properly. you placed out of body
second your block is not even inside body block
so i suggest you rewrite like this
<body>
<div>
<table id="infoTable" class="myTable">
<tr><th></th><th> 1 </th><th> 2 </th><th> 3 </th></tr>
<?php
$sql = "SELECT * FROM `stock` WHERE 1";
$r_query = mysql_query($sql);
//To Table Details
//prints StackerReclaimer_StatusTable;
include("SR_TableStatus.php");
// output data of each row
for ($i=1;$i<5;$i++){ //Rows
$row = mysql_fetch_array($r_query);
if($i == 2 || $i==4)
echo"<tr><td> </td></tr>";
echo"<tr><td class = \"leftCol\"> Bed ".($i)."</td>";
for ($j=1;$j<4;$j++){ //Cols
echo"<td bgcolor=\"#E9E6E5\" id =\"$i$j\"></td>";
/***************************************/
$data = strtoupper($row["sortcode"])." (".(($row["stock"])/1000)."k)";
if( $row["bednumber"] == $i && $row["pilenumber"] == $j ){
// echo"<td bgcolor=\"#E9E6E5\" id = $i$j>".strtoupper($row["sortcode"])." (".(($row["stock"])/1000)."k)</td>";
echo "<script>swapValue($i$j, ".$data.");</script>";
}
/***************************************/
}
echo"</tr>";
}
?>
</table>
</div>
<!-- This script allows user to click on table rows to direct user to More info for that Coal -->
<script>
function swapValue(var location, var data){
var s = document.getElementById(location);
s.value = data;
}
var table = document.getElementById("infoTable");
if (table != null) {
for (var i = 1; i < table.rows.length; i++) {
for (var j = 1; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
tableText(this);
myFunc();
};
}
}
function tableText(tableCell) {
//alert(tableCell.innerHTML);
var Val = tableCell.innerHTML;
Val = Val.substring(0,7);
document.getElementById("searchBox").value = Val;
document.getElementById("searchButton").click();
}
</script>
</body>
I've found a way to get the outcome needed.
After standing back and taking a break to rest the mind & Eyes, I've came back with fresh eyes and have now solved the issue, i was cluttering up the code by using javascript into the php which just adds to a mess if anyone was to decode or read.
so what the code does is reads values from an SQL database using PHP, reads the bednumber(Location(y)) and pileNumber(location(x))
it then makes the table using the for loops I for Rows and J for Columns,
then each column increment you need to update the SQL Query being sent back with the new cell location $i & $j which are held in the bed and pile number values.
i will post the code that now works, but any suggestions or corrections are gratefully appreciated.
<?php
$tableHeader = "<body><center><div><table id=\"infoTable\" class=\"myTable \"><tr><th></th><th> 1 </th><th> 2 </th><th> 3 </th></tr>";
//prints StackerReclaimer_StatusTable;
include("SR_TableStatus.php");
// output data of each row
echo $tableHeader;
/*####################################*/
for ($i=1;$i<5;$i++){
//$row = mysql_fetch_array($r_query);
if($i == 2 || $i==4)
echo"<tr><td> </td></tr>";
echo"<tr><td class = \"leftCol\"> Bed ".($i)."</td>";
for ($j=1;$j<4;$j++){
$sql = "SELECT * FROM `stock` WHERE `bednumber` = $i AND `pilenumber` = $j";
$r_query = mysql_query($sql);
$row = mysql_fetch_array($r_query); //Creates a loop to loop through results
if( $row["bednumber"] == $i && $row["pilenumber"] == $j ){
echo"<td bgcolor=\"#E9E6E5\">".strtoupper($row["sortcode"])." (".(($row["stock"])/1000)."k)</td>";
}
else
echo"<td bgcolor=\"#E9E6E5\"> --- </td>";
}
echo"</tr>";
} /*################################*/
echo "</table></div></center></body>";
?>
<!-- This script allows user to click on table rows to direct user to More info for that Coal -->
<script>
var table = document.getElementById("infoTable");
if (table != null) {
for (var i = 1; i < table.rows.length; i++) {
for (var j = 1; j < table.rows[i].cells.length; j++)
table.rows[i].cells[j].onclick = function () {
tableText(this);
};
}
}
function tableText(tableCell) {
//alert(tableCell.innerHTML);
var Val = tableCell.innerHTML;
Val = Val.substring(0,7);
document.getElementById("searchBox").value = Val;
document.getElementById("searchButton").click();
}
</script>
Related
I want to get the first dropdown menu to get the selected value for the selected dropbox, but I would like to to have all the categories still being in the second dropbox, so I can change the category of the article.
For example, the user chooses a article in the first dropbox, then the category that is associated with that article gets selected, but the user can change the category in the dropbox. Can this be done?
I have tried using Javascript from a previous question , but it's only getting the selected category associated with that article and not all the other categories. What should I do? Does anyone know how this can be done?
<?php $link = mysqli_connect("160.153.129.204", "username", "password", "lvo92");
$db = new mysqli("160.153.129.204", "laurensvo92", "90F0411553l", "lvo92");//set your database handler
$query = "SELECT catid, titel FROM artikelen";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$categories[] = array("catid" => $row['catid'], "val" => $row['titel']);
}
$query = "SELECT catid, cat FROM Categorie";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$subcats[$row['catid']][] = array("catid" => $row['catid'], "val" => $row['cat']);
}
$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);
?>
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].catid);
}
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var testSelectionArray = new Array();
for(var j = 0; j < this.options.length; j++) {
if (this.options[j].selected) {
testSelectionArray.push(this.options[j].value);
}
}
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
var k=0;
for(var i = 0; i < testSelectionArray.length; i++){
catid = testSelectionArray[i];
for(var j = 0; j < subcats[catid].length; j++){
subcatSelect.options[k++] = new Option(subcats[catid][j].val,subcats[catid][j].catid);
}
}
}
</script>
<body onload='loadCategories()'>
<select id='categoriesSelect'>
</select>
<select id='subcatsSelect'>
</select>
I have a table of values in HTML that I want to post. It looks like this:
After the user selects all of the relevant teams, I want to save it into a form, combining all the rows into a form like this:
PHP:
$numRows = 1;
$startMatchNum = 1;
if(isset($_GET['num'])) {
$numRows = $_GET["num"];
$startMatchNum = $_GET["start"];
}
JavaScript:
function getSelectionValue(rowNum, columnNum) {
document.cookie = "rowNum=" + rowNum;
//FOR EXTERNAL PHP FILE
//window.location = "http://example.com/file.php";
var id =
<?php
$index = 0;
$row = 0;
if ( ! empty( $_COOKIE['rowNum'] ) ) {
$row = $_COOKIE['rowNum'];
}
echo '"'.$values[$index].$row.'"';
?>;
var e = document.getElementById(id);
var selectedValue = e.options[e.selectedIndex].value;
}
function postRefreshPage() {
var theForm, newInput1, newInput2, newInput3, newInput4, newInput5, newInput6;
var rows = <?php echo $numRows; ?>;
var nums1 = new Array(rows);
// Start by creating a <form>
theForm = document.createElement('form');
theForm.action = 'addMatch.php';
theForm.method = 'post';
// Next create the <input>s in the form and give them names and values
newInput1 = document.createElement('input');
newInput1.type = 'hidden';
newInput1.name = 'blue1Team';
newInput1.value = "";
for(var i = 0;i < rows;i++) {
newInput1.value += getSelectionValue(i, 0);
if((i + 1) != rows) {
newInput1.value += "|";
}
}
newInput2 = document.createElement('input');
newInput2.type = 'hidden';
newInput2.name = 'blue2Team';
newInput2.value = "";
for(var i = 0;i < rows;i++) {
newInput2.value += getSelectionValue(i, 1);
if((i + 1) != rows) {
newInput2.value += "|";
}
}
newInput3 = document.createElement('input');
newInput3.type = 'hidden';
newInput3.name = 'blue3Team';
newInput3.value = "";
for(var i = 0;i < rows;i++) {
newInput3.value += getSelectionValue(i, 2);
if((i + 1) != rows) {
newInput3.value += "|";
}
}
newInput4 = document.createElement('input');
newInput4.type = 'hidden';
newInput4.name = 'red1Team';
newInput4.value = "";
for(var i = 0;i < rows;i++) {
newInput4.value += getSelectionValue(i, 3);
if((i + 1) != rows) {
newInput4.value += "|";
}
}
newInput5 = document.createElement('input');
newInput5.type = 'hidden';
newInput5.name = 'red2Team';
newInput5.value = "";
for(var i = 0;i < rows;i++) {
newInput5.value += getSelectionValue(i, 4);
if((i + 1) != rows) {
newInput5.value += "|";
}
}
newInput6 = document.createElement('input');
newInput6.type = 'hidden';
newInput6.name = 'red3Team';
newInput6.value = "";
for(var i = 0;i < rows;i++) {
newInput6.value += getSelectionValue(i, 5);
if((i + 1) != rows) {
newInput6.value += "|";
}
}
// Now put everything together...
theForm.appendChild(newInput1);
theForm.appendChild(newInput2);
theForm.appendChild(newInput3);
theForm.appendChild(newInput4);
theForm.appendChild(newInput5);
theForm.appendChild(newInput6);
// ...and it to the DOM...
document.getElementById('hidden_form_container').appendChild(theForm);
// ...and submit it
theForm.submit();
location.reload();
}
Then, after it refreshes, it runs this PHP code:
if($_POST) {
$blueTeam1 = explode ("|", $_POST['blueTeam1']);
$blueTeam2 = explode ("|", $_POST['blueTeam2']);
$blueTeam3 = explode ("|", $_POST['blueTeam3']);
$redTeam1 = explode ("|", $_POST['redTeam1']);
$redTeam2 = explode ("|", $_POST['redTeam2']);
$redTeam3 = explode ("|", $_POST['redTeam3']);
for($i = 0;i < $numRows;$i++) {
$matchNumber = $i + 1;
$query = "INSERT INTO match_info (matchNumber, blueTeam1, blueTeam2, blueTeam3, redTeam1, redTeam2, redTeam3)
VALUES ('$matchNumber','$blueTeam1[$i]','$blueTeam2[$i]','$blueTeam3[$i]','$redTeam1[$i]','$redTeam2[$i]','$redTeam3[$i]')";
$mysqli->query($query);
}
}
However, it doesn't seem to be submitting. Any help is greatly appreciated!
EDIT: I found the error, but I don't know how to fix it. In the Javascript code, the getSelectionValue function returns undefined, but I'm not sure why.
You can try to remove
location.reload();
in getSelectionValue() function, because you submit but in the same time you reload the initial script.
I figured it out. It was a variety of issues. First of all, the IDs in my PHP code didn't match the IDs in the JavaScript table. Secondly, my use of cookies to pass JavaScript variables to PHP didn't work, so I copied the PHP array I wanted to access and set it again in JavaScript. So, the function getSelectionValue(rowNum, columnNum); doesn't need to access the PHP code. Lastly, my table in the database didn't have the matchNumber column in it, so the whole process failed.
Thanks to all those that helped!
I have the following code:
while ($row = $result->fetch_assoc()) {
echo "<div class='competitor' style='background: ".$row['Colour'].";'>";
echo "<div class='competitorname'>".$row['CompetitorName']."</div><br>";
echo "<div class='competitorscore' id='".$row['CompetitorID']."'>";
echo"<label id='".$row['CompetitorName']."'></label></div>";
echo "<input type='button' value='Increase' id='inc' onclick='incNumber()'/>";
echo "<input type='button' value='Decrease' id='dec' onclick='decNumber()'/>";
}
The code is linked to the following script:
var i = 0;
function incNumber() {
if (i < 10) {
i++;
} else if (i = 10) {
i = 0;
}
document.getElementById('display').innerHTML = i;
}
function decNumber() {
if (i > 0) {
--i;
} else if (i = 0) {
i = 10;
}
document.getElementById('display').innerHTML = i;
}
The code creates a scoreboard. It creates a div for each team with a score for that team.
The problem I'm having is that the "Increase" and "Decrease" buttons are increasing and decreasing the score on only one team (the first one). This is because the script is looking for the label with the id='display' and linking every button to that one.
My question is, how can I create a different ID for each team that works with the script so that each increase/decrease button is linked to a different team?
Use the CompetitorID as a parameter to the increment and decrement functions to tell it which row to affect. Your label:
<label id='display".$row['CompetitorID']."'></label>
Your button onclick event:
onclick='incNumber(".$row['CompetitorID'].")'
Then your JavaScript:
function incNumber(id) {
if (i < 10) {
i++;
} else if (i = 10) {
i = 0;
}
document.getElementById('display' + id).innerHTML = i;
}
Edit
For the issue in the comments, echo a hidden field which stores the value for each team:
<input type='hidden' id='score".$row['CompetitorID']."' value='0'/>
Then remove the global var i = 0; and modify your functions similar to this:
function incNumber(id) {
// Get the score input
var scoreField = document.getElementById('score' + id);
// Get the value
var i = parseInt(scoreField.value);
if (i < 10) {
i++;
} else if (i = 10) {
i = 0;
}
// Set the visual score
document.getElementById('display' + id).innerHTML = i;
// Set the score input to the new score
scoreField.value = i;
}
You have a $row['CompetitorID'] value which is, presumably, unique. Append that to the IDs you are using.
I am creating an internal web tool that inserts data into a database. I was trying to find out how to create a three-tier dropdown selection, where I would insert the third dropdown's value into the DB.
I stumbled across this answer here:
Populate another select dropdown from database based on dropdown selection
But was done as a two tier dropdown.
My php code is this:
<?php
require 'connect.php';
$query = "SELECT customer_id,customer FROM schema.customer";
$result = $DB_con->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$categories[] = array("customer_id" => $row['customer_id'], "customer" => $row['customer']);
}
$query = "SELECT contract_id, customer_id, contract FROM schema.contract";
$result = $DB_con->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$subcats[$row['customer_id']][] = array("contract_id" => $row['contract_id'], "contract" => $row['contract']);
}
// Third dropdown which isn't originally included with the previous answer
$query = "SELECT subcontract_id, contract_id, subcontract FROM schema.subcontract";
$result = $DB_con->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$subsubcats[$row['contract_id']][] = array("subcontract_id" => $row['subcontract_id'], "subcontract" => $row['subcontract']);
}
$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);
$jsonSubSubCats = json_encode($subsubcats);
?>
Now, the given answer was this:
<head>
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
//Below wasn't part of the answer
echo "var subsubcats = $jsonSubSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].customer,categories[i].customer_id);
}
}
function updateSubCats(){
var catSelect = this;
var customer_id = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[customer_id].length; i++){
subcatSelect.options[i] = new Option(subcats[customer_id][i].contract,subcats[customer_id][i].contract_id);
}
}
</script>
</head>
<body onload='loadCategories()'>
<select id='categoriesSelect'>
</select>
<select id='subcatsSelect'>
</select>
</body>
</html>
But I needed help with the third tier options based from the second dropdown selection. Thanks in Advance. :)
Was able to figure it out.
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
echo "var subsubcats = $jsonSubSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].customer,categories[i].customer_id);
}
}
function updateSubCats(){
var customer_id = this.value;
var subcatSelect = document.getElementById("subcatsSelect")
subcatSelect.onchange = updateSubSubCats;;
for(var i = 0; i < subcats[customer_id].length; i++){
subcatSelect.options[i] = new Option(subcats[customer_id][i].contract,subcats[customer_id][i].contract_id);
}
}
function updateSubSubCats(){
var subsubcatSelect = this;
var contract_id = this.value;
var subsubcatSelect = document.getElementById("subsubcatsSelect");
subsubcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subsubcats[contract_id].length; i++){
subsubcatSelect.options[i] = new Option(subsubcats[contract_id][i].subcontract,subsubcats[contract_id][i].subcontract_id);
}
}
</script>
as before the below code is in a while loop . it out puts values id=pro0 then next loop through i get id=pro1 and if i have another record i get id=pro3
print "<td><input style=\"text-align:center\" type=\"text\" name=\"productitemsupdate_$num\" value=\"$row[productitems]\" size=\"5\" id=\"pro$num\"></td>";
the above code works with
var pro = document.getElementById('pro0');
what im after is a loop in java script which will take the last $num from the php from and use that for the amount of times to loop the javascript function.
something like this i think
var i=0;
while (i<=$num) {
var pro[i] = document.getElementById('pro'[i]);
if (pro[i].value == "") {
inlineMsg('pro'[i],'This cannot Be blank'[i],10);
return false;
} else {
i++;
}
}
breaks when it is false when all fields are right it is true.
if i get this working it will save me guessing how many variable to check.
i have tried this but i cant this working either
var i=0;
var pro[i] = document.getElementById('pro' + i);
for(var i = 0; i < <?php $num ?>; i++) {
if(pro[i].value == "")
alert("You entered: " + pro[i].value)
return false;
}
this works but only for the first line. if the 2nd line is emtpy and the first line is not it does not produce the alert
var i=0;
for(var i = 0; i < 3; i++) {
var pro = document.getElementById('pro' + i);
if(pro.value == "")
alert("You entered: " + pro[i].value)
return false;
}
i also changed the $num variable to a static number for my test record to see if it was my variable not being passed and it still did't work for the 2nd record any ideas
thanks
steve
working solution thanks for your help
var i=0;
var pro = [];
for(var i = 0; i < 2; i++) {
pro[i] = document.getElementById('pro' + i);
if(pro[i].value == ""){
alert("You entered: " + pro[i].value)
return false;}
}
PHP is server-side. JavaScript is client-side. If you want to insert a PHP variable into JavaScript, you have to treat your JS like HTML and use PHP to create the script. Something like this:
<!-- ... -->
<script>
var num = <?php echo $num ?>;
</script>
<!-- ... -->
Then you can use this value of num elsewhere, even in external scripts (as long as num is declared beforehand).
Edit
Your if statement in the for loop is missing braces. Try this:
var i=0,
pro[i] = document.getElementById('pro' + i);
for(var i = 0; i < <?php echo $num ?>; i++) {
if(pro[i].value == "")
{
alert("You entered: " + pro[i].value)
return false;
}
}
Make sure that this JS is actually being processed by PHP. The easiest way to do that is to put the code into an inline <script> tag.
In javascript, you concatenate strings using +. Therefore, you need to write
pro[i] = document.getElementById('pro' + i);
For your loop, that'd look something like
for(var i = 0; i < <?php echo $num ?>; i++) {
...
}
Complete code:
var i=0;
var pro = [];
for(var i = 0; i < <?php echo $num ?>; i++) {
pro[i] = document.getElementById('pro' + i);
if(pro[i].value == "") {
alert("You entered: " + pro[i].value)
return false;
}
}
If you don't need the actual array for anything, for later, you could simply do:
var i=0;
for(var i = 0; i < <?php echo $num ?>; i++) {
var pro = document.getElementById('pro' + i);
if(pro.value == "") {
alert("You entered: " + pro.value)
return false;
}
}
What ever your PHP (not my expertise), here is an example looping through: http://jsfiddle.net/UpG57/