Select dropdown option and display table (javascript) - javascript

With a SELECT query I obtain an array of 7 names, create a dropdown list and each name is a table which is then hidden.
I want to click on the name in the dropdown list and display the table.
I am not receiving any errors but the following code only displays the first table in the array no matter what option is selected. I have little knowledge of javascript and the function has been cobbled together from various queries on the site.
Javascript:
function changeOpt(clicked) {
var x = document.getElementById("optChange");
var optVal = x.options[x.selectedIndex].value;
for(var i =0; i<x.length;i++){
if(optVal = document.getElementById('datath'))
document.getElementById('data').style.display = 'block';
}
}
HTML/PHP:
while($row = mysqli_fetch_array($result))
{
$array = $row;
//echo '<pre>'.print_r($array).'</pre>';
echo '<table id="data" style="display:none;">';
echo '<tr><td>You searched for:</td></tr>';
echo '<tr><th id="datath">'.$row[0].'</th><th>'.$row[1].'</th><th>'.$row[2].'</th>';
echo '</tr>';
echo '</table>';
$option .= '<option value = "'.$row['1'].'">'.$row['1'].'</option>';
}
?>
<form method="post" action="#" id="my_form" >
<select id="optChange" name="opt" onchange="changeOpt(this.id)">
<option><--select a name--></option>
<option><?php echo $option; ?></option>
</select>
<input type="button" name="submit" value="submit" >
</form>
Am I completely off-beam ? Can someone give me some guidance please to get my code straight.

Related

How do I get button's ID from a list of buttons?

I haven't worked much with php and javascript and was hoping to get some help. I want to be able to detect which button was clicked exactly. I'm creating one button per row but I don't know how to figure out what row the click was made in. This is what I have so far...
# Get all the table data from the database
$getData = mysqli_query($conn, "SELECT * FROM `query_table`") or die ("Error occured while selecting!");
// echo '<form method="post" action="index.php">';
echo '<table border="1">';
echo '<tr>';
echo '<td>Questions</td>';
echo '<td>Likes</td>';
echo '<td></td>';
echo '</tr>';
# Loop through each row and print out the question
while ($row = mysqli_fetch_array($getData)) {
echo '<tr>';
echo '<td>';
echo $row['Question'];
echo '</td>';
echo '<td>';
echo $row['Likes'];
echo '</td>';
echo '<td>';
?>
<input type="button" id="myButton" value="Like" onclick="myFunc(<?=$row['ID']?>)" />
<?php
echo '</td>';
echo '</tr>';
}
echo '</table>';
// echo '</form>';
echo '<p id="text"></p>';
mysqli_close($conn);
?>
<script type="text/javascript">
function myFunc(id) {
document.getElementById("text").innerHTML = id;
}
</script>
So far this prints out the row id where the button was clicked, but I don't suppose I can assign that parameter value directly to a php variable that I can then use for mysql queries. How is stuff like this normally done, please help.
<input type="button" data-id="<?=$row['ID']?>" value="Like" onclick="myFunc(this)">
and
<script type="text/javascript">
function myFunc(button) {
document.getElementById("text").innerHTML = button.getAttribute('data-id');
}
</script>
In JavaScript the token "this" refers to the context in which the code is running which in this case is the button. Store custom data in attributes prefixed with data- to ensure they are not disturbed - standard practise.

checked checkbox will remain through pagination

i am doing a php script wherein I need to remember the checked checkbox and save it all the database. Unfortunately, my code save only the current page where I checked the checkbox but the other checked box became unchecked.
Example In Page 1 I checked 3 items, on the second page I checked I tem. When I click the submit button I only got the checked item of the current page. And when I go back to the previous page the item that I checked became unchecked.How can I preserved and save the value of my checked checkbox through pagination?
here is my code for CreateTest.php
<html>
<body>
<?php
ob_start();
session_start();
include("connect.php");
error_reporting(0);
$item_per_page=10;
$results = mysqli_query($con,"SELECT COUNT(*) FROM tblitem");
$get_total_rows = mysqli_fetch_array($results); //total records
//break total records into pages
$pages = ceil($get_total_rows[0]/$item_per_page);
//create pagination
if($pages > 1)
{
$pagination = '';
$pagination .= '<ul class="paginate">';
for($i = 1; $i<=$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '</ul>';
}
?><!DOCTYPE html>
<script type="text/javascript">
$(document).ready(function() {
$("#results").load("fetch_pages.php", {'page':0}, function() {$("#1-page").addClass('active');}); //initial page number to load
$(".paginate_click").click(function (e) {
$("#results").prepend('<div class="loading-indication"><img src="ajax-loader.gif" /> Loading...</div>');
var clicked_id = $(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
$("#results").load("fetch_pages.php", {'page':(page_num-1)}, function(){
});
$(this).addClass('active'); //add active class to currently clicked element (style purpose)
return false; //prevent going to herf link
});
});
</script>
<form name="myform" action="CreateTest.php" method="POST" onsubmit="return checkTheBox();" autocomplete="off">
<body>
<?php
if(isset($_POST['save'])){
$testPrice = $_POST['testPrice'];
$testName = $_POST['testName'];
$items = $_POST['items'];
$quantity = $_POST['quantity'];
$testDept = $_POST['testDept'];
$measurement = $_POST['measurement'];
global $con;
Tool::SP_Tests_Insert(strip_tags(ucwords($testName)), $testPrice, $testDept);
$result = mysqli_query($con, "SELECT MAX(TestID) FROM lis.tbltests");
$data= mysqli_fetch_array($result);
$testID=$data[0];
foreach ($items as $key => $value){
$checkedItem[] = $value;
echo $value, " | ",$quantity[$key], " | ",$measurement[$key], "<br>";
mysqli_query($con,"INSERT INTO tbltestitem (TestID, ItemID, ItemQuantity, ItemMeasurement) VALUES ($testID, $value, '$quantity[$key]', '$measurement[$key]')");
}
echo "<script type='text/javascript'>alert('Succesfully added test!')</script>";
$site_url = "tests.php";
echo "<script language=\"JavaScript\">{location.href=\"$site_url\"; self.focus(); }</script>";
}else if(!isset($_POST['save'])){
$selectDept='';
$result= mysqli_query($con,"select * from tbldepartment");
$selectDept.="<option value=''>Select Department:</option>";
while($data = mysqli_fetch_array($result)){
$selectDept.="<option value='{$data['DeptID']}'>{$data['DeptName']}</option>";
}
?>
<td style="vertical-align: top;">
<body>
<div id="container" align="center">
<div id="title">Create Test</div>
<div id="a">Input Test Name:</div><div id="b"><input type="text" name="testName" id="myTextBox" onkeyup="saveValue();" ></div>
<div id="a">Input Test Price:</div><div id="b"><input type="number" name="testPrice"></div>
<div id="a">Select Department:</div><div id="b"><select name="testDept" ><?php echo $selectDept; ?></select></div>
<div id="results"></div><div id="a"><?php echo $pagination; ?></div>
<div align="right" style="padding: 10px;"><input type="submit" name="save" value="Submit"></div> </div>
<?php
}
?>
</body>
</html>
This is my fetch_pages.php code.
this php page help me to keep the textbox values through pagination through jquery it will be loaded without going the another page of pagination
<?php
include("connect.php");
require_once('classes/tool.php');
$item_per_page=10;
//sanitize post value
$page_number = $_POST["page"];
//validate page number is really numaric
if(!is_numeric($page_number)){die('Invalid page number!');}
//get current starting point of records
$position = ($page_number * $item_per_page);
//Limit our results within a specified range.
$results = mysqli_query($con,"SELECT * FROM tblitem ORDER BY ItemID ASC LIMIT $position, $item_per_page");
$connection=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
$selectMeasure='';
$measurements = Tool::SP_Measurement_Select();
foreach($measurements as $measure) {
$selectMeasure.='<option value=' . $measure['MeaName'] . '>' . $measure['MeaName'] . '</option>';
$i=0;
while($item = mysqli_fetch_array($results))
{
echo "<div id='a'><input type='checkbox' name='items[$i]' id='item[]' value='". $item['ItemID'] ."' >".$item['ItemName']."</div>";
echo "<div id='b'><input type='number' name='quantity[$i]' class='quantity' /></div>";
echo "<div id='b'><select name='measurement[$i]' class='quantity'>'".$selectMeasure."'</select></div>";
$i++;
}
?>
Hope you can help me. Thanks in advance
Ugg... way too much code to look through.
The short answer, however, is that you pass values from one form to another using <input type-"hidden"...> markup.
Warning, code type free-hand
Page1.php
<form action="page2.php">
<div>
<input type="checkbox" name="test1">
</div>
</form>
Page2.php
<?php
if (is_set($_REQUEST["test1"])) {
$test1 = $_REQUEST["test1"];
} else {
$test1 = false;
}
<form action="page3.php">
<div>
<input type="hidden" name="test1" value="<?php echo $test1 ?>">
</div>
</form>
Page3.php
<?php
$test1 = $_REQUEST["test1"];
?>

Retain Data Recieved from Database on HTML form

<?php
include_once 'database_connect.php';
$conn = new dbconnection();
$dbcon = $conn->connect();
if (!$dbcon) {
die("Fail".mysqli_error($dbcon));
}
?>
<html>
<head>
<title></title>
<script type="text/javascript"></script>
</head>
<body>
<form name="frm" method="post" action='<?php echo $_SERVER['PHP_SELF']; ?>'>
<table width="50%" border="1" cellpadding="3" cellspacing="3" align="center">
<?php
$value1 = array();
$select_query = "SELECT Distinct branch FROM subjects";
$result = mysqli_query($dbcon, $select_query);
if (!$result) {
die("Fail".mysqli_error($dbcon));
}
while ($row = mysqli_fetch_array($result)) {
$value1[] = $row['branch'];
}
?>
<tr>
<td>Branch
<td><select name="branch" id="branch" onchange="document.frm.submit();">
<option>Select Branch</option>
<?php
foreach ($value1 as $gets)
echo "<option value={$gets}>{$gets}</option>";
?>
</select>
<?php
$value2 = array();
if (isset($_POST['branch'])) {
$branch = $_POST['branch'];
$getsub_query = "SELECT sub_code FROM subjects where branch='$branch'";
$result2 = mysqli_query($dbcon, $getsub_query);
if (!$result2) {
die("Fail\n".mysqli_error($dbcon));
}
while ($row1 = mysqli_fetch_array($result2)) {
$value2[] = $row1['sub_code'];
}
}
?>
<tr>
<td>Subject Code
<td><select name="subcode" id="subcode">
<option>Subject Code</option>
<?php
foreach ($value2 as $gets)
echo "<option value={$gets}>{$gets}</option>";
?>
</select>
This code gets the first drop down list branch from data base. When we select value from it, second drop down list get filled from database . but problem is when i select option in first drop down list, the selected option does not remain their in first drop down list . but second drop down list fills correctly. i want that option i have selected should remain selected. Like its state should be changed. I think first drop down list gets filled again on form load.
You have to mention in your html that the option is indeed selected.
Try replacing
echo "<option value={$gets}>{$gets}</option>";
By
$selected = '';
if (isset($_POST['branch'] && $gets==$_POST['branch']) {
$selected = ' selected="selected"';
}
echo "<option value={$gets}".$selected.">{$gets}</option>";

SQL Generated select menu, updating textbox based on related value

Some Background information:
I have a table with two fields, TECHNAME and TECHCOLOR
What I am trying to do is:
Have a SQL generated Drop down menu based on TECHNAME (DONE)
Have TECHCOLOR update in text box when TECHNAME is selected (ISSUE IS HERE)
What is wrong
Currently, the textbox is showing TECHNAME insead of TECHCOLOR
Code
JavaScript:
<script type="text/javascript">
function load_value(value)
{
document.getElementById("test").value=value;
}
</script>
HTML/PHP:
<table>
<form method="post" action="">
<?php
$select_box='<select name="edittech" id="edittech" onchange="javascript:load_value(this.value);">';
$input="";
$result = $conn->query("select * from techs");
while ($row = $result->fetch_assoc()) {
$select_box .='<option id="name" value="'.$row["TECHNAME"].'">'.$row['TECHNAME'].'</option>';
}
$input ='<input type="text" name="test" id="test" value="" />';
echo $select_box."</select>";
echo $input;
?>
Thanks in advance! :D
When you submit the form, is the value for your edittech dropdown list used at all? If it isn't then you can simply change the value part of your dropdown to be TECHCOLOR and it will still show TECHNAME on the dropdown.
while ($row = $result->fetch_assoc()) {
$select_box .= "<option id=\"name\" value=\"{$row['TECHCOLOR']}\">{$row['TECHNAME']}</option>";
}

Trying to make a each row in a table that is embedded in a form clickable to make a project work as designed (no submit button)

I have fixed the problem of the table working within a form. I just added an extra <td> field and created a hidden input field within it that will POST a separate tipID for each tip in the table. The entire table is also wrapped with the form tag to get the tipID to POST to the next page.
Now I need to know how make each individual table row send the data from the form kind of like each one being a button or making a hidden button click onclick of one of these table rows.
<form method="post" action="tips.php">
<div id="tippanel">
<table id="tippabl">
<tbody>
<?php if(!empty($tips))
while ($recd = mysql_fetch_array($tips, MYSQL_ASSOC)) {
echo "<tr> <td class='tiptxt' >"; echo $recd['tip_desc']; echo "</td> <td class='tiptime'>";
echo "<span>".date('H:i', strtotime($recd['datetime']))."</span>"; echo "</br>";
echo date('m-d-y', strtotime($recd['datetime'])); echo"</td><td><input type=";
echo '"hidden" '; echo 'name='; echo '"tip_id" '; echo 'value="';
echo ($recd['tip_id']); echo'"></td></tr>';
}
?>
</tbody>
</table>
</div>
</form>
My next page will use the query below and echo the full tip_desc since a tip can be several hundred characters. It will also have a text area in which an admin can send a message back to the original user.
My PHP and query should look like this on the next page:
<?php
$tipID = $_POST['tipID'];
mysql_query="SELECT * FROM tips WHERE tipID = $tipID";
?>
Just surround your table into a form, place a hidden input field into it.
<form action="tips.php">
<input name="tipID" type="hidden" value="id" />
<div id="tippanel">
<table id="tippabl">
<tbody>
<?php
if(!empty($tips)) {
while ($recd = mysql_fetch_array($tips, MYSQL_ASSOC)) {
echo "<tr> <td class='tiptxt' >"; echo $recd['tipDescription'];
echo "</td> <td class='tiptime'>";
echo "<span>".date('H:i', strtotime($recd['dateTime']))."</span>";
echo "</br>"; echo date('m-d-y', strtotime($recd['dateTime']));
echo"</td></tr>";
}
}
?>
</tbody>
</table>
</div>
</form>
Have a look at this to make your rows clickable. Working demo
function addRowHandlers() {
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row)
{
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
alert("id:" + id);
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
Credit: SolutionYogi
Ref: Adding an onclick event to a table row

Categories

Resources