Clicking the row of the table and displaying it to text field - javascript

I have text field inside the table, and also the data below in it..I want to display the data to text field after clicking the row.
I tried these code but nothing happens. Help me please.
These are the code for the table.
<table id="tableqwe">
<tr>
<th>Name</th>
<th>Id Number</th>
<th>Course</th>
<th>Year level</th>
<th>School Year</th>
<th>Semester</th>
<th></th>
</tr>
<tr>
<th><input type="Text" id="name1" name="name1" style="width:200px;"></th>
<th><input type="Text" id="idnumber2" name="idnumber2" style="width:200px;"></th>
<th><input type="Text" id="course3" name="course3" style="width:80px;"></th>
<th><input type="Text" id="yearlvl4" name="yearlvl4" style="width:200px;"></th>
<th><input type="Text" id="schoolyear5" name="schoolyear5" style="width:150px;"></th>
<th><input type="Text" id="semester6" name="semester6" style="width:100px;"></th>
<th><input type="button" value="Add" class="btntable edit" style="width:50px;"></th>
</tr>
<?php
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['Id_number'] . "</td>";
echo "<td>" . $row['course'] . "</td>";
echo "<td>" . $row['year_level'] . "</td>";
echo "<td>" . $row['school_year'] . "</td>";
echo "<td>" . $row['semester'] . "</td>";
echo "<td>"?><input type="button" class="btntable delete" value="Delete" style="width:50px;"><?php
echo "</tr>";
}
?>
</table>
And these are the javascript code...
<script>
var table1 = document.getElementById('tableqwe');
for(var i = 2; i < table1.rows.length; i++)
{
table.rows[i].onclick = function()
{
rIndex = this.rowIndex;
console.log(rIndex);
document.getElementsByName("name1").value = this.cells[0].innerHTML;
document.getElementsByName("idnumber2").value = this.cells[1].innerHTML;
document.getElementsByName("course3").value = this.cells[2].innerHTML;
document.getElementsByName("yearlvl4").value = this.cells[3].innerHTML;
document.getElementsByName("schoolyear5").value = this.cells[4].innerHTML;
document.getElementsByName("semester6").value = this.cells[5].innerHTML;
}
}
</script>
Can someone help me with this.! All I want is if I click any row of the table, it will directly display it to the text field.

You should use HTML DOM getElementById() Method to get the element with the specified ID.
HTML DOM getElementsByName() Method Get all elements with the specified name.
You have to edit your js script as follows.
If you are using 'HTML DOM getElementsByName() Method' to assign value to that specific element you should use it as document.getElementsByName("name1")[0].value="value". Since this method returns the collection of objects having the same name passed as it's parameter.
If you are using the HTML DOM getElementById() you can assign values into it by using the code as document.getElementById("idofelement").value="value".
An example is given in the snippet below.
var table1 = document.getElementById('tableqwe');
for(var i = 2; i < table1.rows.length; i++)
{
table1.rows[i].onclick = function()
{
rIndex = this.rowIndex;
console.log(this.cells[0].innerHTML);
document.getElementById("name1").value = this.cells[0].innerHTML;
console.log(document.getElementsByName("name1")[0].value);
document.getElementById("idnumber2").value = this.cells[1].innerHTML;
document.getElementById("course3").value = this.cells[2].innerHTML;
document.getElementById("yearlvl4").value = this.cells[3].innerHTML;
document.getElementById("schoolyear5").value = this.cells[4].innerHTML;
document.getElementById("semester6").value = this.cells[5].innerHTML;
}
}
<table id="tableqwe">
<tr>
<th>Name</th>
<th>Id Number</th>
<th>Course</th>
<th>Year level</th>
<th>School Year</th>
<th>Semester</th>
<th></th>
</tr>
<tr>
<th><input type="Text" id="name1" name="name1" style="width:200px;"></th>
<th><input type="Text" id="idnumber2" name="idnumber2" style="width:200px;"></th>
<th><input type="Text" id="course3" name="course3" style="width:80px;"></th>
<th><input type="Text" id="yearlvl4" name="yearlvl4" style="width:200px;"></th>
<th><input type="Text" id="schoolyear5" name="schoolyear5" style="width:150px;"></th>
<th><input type="Text" id="semester6" name="semester6" style="width:100px;"></th>
<th><input type="button" value="Add" class="btntable edit" style="width:50px;"></th>
</tr>
<tr>
<td>name</td>
<td>12</td>
<td>Course</td>
<td>Course 12</td>
<td>School year 12</td>
<td>School year 12</td>
<td><input type="button" class="btntable delete" value="Delete" style="width:50px;"></tr>;
</table>

Change the code like this.
<?php
while($row = mysqli_fetch_array($result)) {
echo "<tr contenteditable = 'true' id='name' data-name= '//php variable like $id '>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>"?><input type="button" class="btntable delete" value="Delete" style="width:50px;"><?php
echo "</tr>";
}
?>
then change your javascript to like this (Im coding it Jquery and change it you want.)
<Script>
$(document).on('click', '#button Id or Class here', function(){
//get id of user updates
var id = $(this).data("name");
// get values
var val = $(this).text();
});
</script>
this the solution. if is this help for your leave a comment.

Related

how to hide table row by applying filter variables using javascript?

FYI- I am making a timesheet project using PHP and MySQL
I am new to PHP, I tried to use PHP make HTML table rows and assign them row id, but the problem is that my table is displaying a large number of rows, so I made a javascript filter to display only rows which match with the filter values
But the problem is I don't how to use row id and then use their values to get compared with the javascript variable and based on match its CSS property is set to display (if matched) or hide (if not matched).
Is there any other way to do this?
Here is Filter Section.
<div class='row'>
<div class='col'>
<label>Select Filters:</label>
</div>
</div>
<div class='row'>
<div class='col'>
<div class='filter'>
<label>EmpID:</label>
<select id='empid_select'>
<option value='' >select</option>
<?php
include('connection.php');
$stmt = $conn->prepare('SELECT `EmpID`, `Name` FROM `employee_data` ORDER BY `EmpID` ');
if($stmt->execute()){
$stmt->bind_result($empid, $empname);
while($stmt->fetch()){
echo "<option value='$empid'>$empid - $empname</option>";
}
}else{
printf("Error: %s\n", $conn->error);
}
$stmt->close();
?>
</select>
<label>Project Code:</label>
<select id='projectcode_select'>
<option value=''>Select</option>
<?php
include('connection.php');
$stmt = $conn->prepare('SELECT `Projectcode`, `Title` FROM `Projectcodetbl` ORDER BY `Projectcode` ASC ');
if($stmt->execute()){
$stmt->bind_result($projectcode, $title);
while($stmt->fetch()){
echo "<option value='$projectcode'>$projectcode - $title</option>";
}
}else{
printf("Error: %s\n", $conn->error);
}
?>
</select>
<label>Start Date: </label>
<input type='date' name='startdate-filter' id='startdate-filter' >
<label>End Date: </label>
<input type='date' name='enddate-filter' id='enddate-filter' >
<button name='notseen-entries-filter-button' id='notseen-entries-filter-button'>Apply</button>
</div>
</div>
</div>
Here is my script to get value form the filter section.
<script>
$(document).ready(function(){
$('[name="notseen-entries-filter-button"]').click(function(e){
var empid = $('#empid_select option:selected').val();
var projectcode = $('#projectcode_select option:selected').val();
var startdate = $('#startdate-filter').val();
var enddate = $('#enddate-filter').val();
alert("Filter rows with values EmpID: "+empid+", ProjectCode: "+projectcode+", StartDate: "+startdate+", EndDate: "+enddate);
});
});
</script>
PHP Function for displaying the table heading
function displayTableHeading(){
echo "
<form action='selected.php' method='post'>
<table border='1' cellpadding='10' cellspacing='0'>
<tr>
<th colspan='13'><button type='submit' class='btn btn-outline-primary' style='border-radius: 3px;'><i class='fas fa-edit' style='margin-right:10px;'></i>Update</button>
</tr>
<tr>
<th>Row</th>
<th>EmpID - Name</th>
<th>Date</th>
<th>Start Time</th>
<th>End Time</th>
<th>Hrs</th>
<th>Project Code</th>
<th>Task Performed</th>
<th>Invoice Num</th>
<th colspan=3>Status</th>
</tr>";
}
PHP Function for displaying the table rows.
//Webpage Table Row
function displayTableRow($row, $i, $empid){
$notBillable = intval( $row['Status'] )==1 ? 'checked' : '';
$billablePlusNotInvoiced = intval( $row['Status'] )==2 ? 'checked' : '';
$billablePlusInvoiced = intval( $row['Status'] )==3 ? 'checked' : '';
printf("
<!-- record: %d -->
<tr id='%d'>
<td><input type='text' size='1' value='%d' ></td>
<td><input type='text' size='10' name='empid[]' value='%s'></td>
<td><input type='text' size='7' name='date[]' value='%s' ></td>
<td><input type='text' size='5' name='stime[]' value='%s' ></td>
<td><input type='text' size='5' name='etime[]' value='%s' ></td>
<td><input type='text' size='1' name='hours[]' value='%s' ></td>
<td><b><input type='text' size='9' name='projectcode[]' value='%s' ></b></td>
<td><input type='text' size='30' name='taskperformed[]' value='%s' ></td>
<td><input type='text' size='8' name='invoicenum[]' value='%s' ></td>
<td><input type='radio' name='status_{$i}[]' value='1' %s/>NB</td>
<td><input type='radio' name='status_{$i}[]' value='2' %s/>B+NI</td>
<td><input type='radio' name='status_{$i}[]' value='3' %s/>B+I</td>
<input type='hidden' name='modifieddate[]' value='%s'>
</tr>",
$i,$i,$i,
getEmpNameById($empid),
$row['Date'],
$row['StartTime'],
$row['EndTime'],
$row['NoOfHours'],
$row['ProjectCode'],
$row['TaskPerformed'],
$row['InvoiceNumber'],
$notBillable,
$billablePlusNotInvoiced,
$billablePlusInvoiced,
$row['ModifiedDate']
);
}
PHP code for calling above function and displaying the HTML table.
$sumNoOfHours = 0.0;
displayTableHeading();
$i=1;
foreach($empid_array as $code){
//split the $code variable to get the emp id
$codearr = explode(" - ", $code);
$empid = $codearr[0];
$selectSql = "SELECT * FROM `mastertbl` WHERE EmpID = '$empid' AND Status = 0 ORDER BY Date DESC, ModifiedDate DESC";
$result = mysqli_query($conn, $selectSql) or die( mysqli_error($conn));
while($row = mysqli_fetch_array($result))
{
$sumNoOfHours = $sumNoOfHours + $row['NoOfHours'];
displayTableRow($row, $i, $empid);
$i++;
}
}

How to get a javascript function working inside a php table?

I am trying to get the Multiply function to run and multiply the Order Quantity times the item price. I cannot get the function to run inside the PHP loop using the oninput attribute.
<script type="text/javascript">
function Multiply() {
var myBox1 = document.getElementById('editedvalues[]').value;
var myBox2 = document.getElementById('price').value;
var result = document.getElementById('result');
var myResult = myBox1 * myBox2;
result.value = myResult;
}
</script>
<?php
$sql = "SELECT item_price.item_id,
item_price.ITEM_NAME,
suggested_qty,
Price_item
FROM item_price
JOIN suggested_item ON item_price.ITEM_NAME = suggested_item.ITEM_NAME";
$result = $conn->query($sql);
?>
form action="#" method="post">
<tr>
<th> ID</th>
<th>Item Name</th>
<th>Suggested Quantity</th>
<th>Price</th>
<th>OrderQuanity</th>
<th>Total Cost</th>
</tr>
<?php
while ($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>{$row['item_id']}</td>";
echo "<td>{$row['ITEM_NAME']}</td>";
echo "<td>{$row['suggested_qty']}</td>";
echo "<td>{$row['Price_item']}</td>";
echo "<td><input type='text' name='editedvalues[]' value='{$row['suggested_qty']}' oninput='Multiply()' /></td>";
echo "<td><input name='result' /></td>";
echo "</tr>";
}
?>
You're using the document.getElementById function to refer to elements, but in addition to the fact that there are multiple inputs that this function can run on, your inputs don't even have an ID.
To make sure this function works on the input in question, you'll need to look at the target of the event instead of ignoring it. As well, you should use proper event binding instead of inline oninput attributes.
You also weren't using a table element, and you should really break out of PHP for huge blocks of HTML code.
This would be much easier using some framework like jQuery, but this should work.
var nodes = document.getElementsByClassName("qtyinput");
for (var i = 0; i < nodes.length; i++) {
nodes[i].addEventListener('input', multiply, false);
}
function multiply(e) {
var qty = e.target.value;
var price = e.target.parentNode.parentNode.getElementsByClassName("pricetd")[0].textContent;
var result = e.target.parentNode.parentNode.getElementsByClassName("resultinput")[0];
var myResult = qty * price;
result.value = myResult;
}
<?php
$sql = "SELECT item_price.item_id,
item_price.ITEM_NAME,
suggested_qty,
Price_item
FROM item_price
JOIN suggested_item ON item_price.ITEM_NAME = suggested_item.ITEM_NAME";
$result = $conn->query($sql);
?>
<form action="#" method="post">
<table>
<tr>
<th> ID</th>
<th>Item Name</th>
<th>Suggested Quantity</th>
<th>Price</th>
<th>OrderQuanity</th>
<th>Total Cost</th>
</tr>
<!-- test data for snippet -->
<tr>
<td>111</td>
<td>Test item</td>
<td>4</td>
<td class="pricetd">40</td>
<td>
<input type="text" name="editedvalues[]" class="qtyinput" value="4" />
</td>
<td><input name='result' class="resultinput" /></td>
</tr>
<?php while ($row = $result->fetch_assoc()) :?>
<tr>
<td><?=$row["item_id"]?></td>
<td><?=$row["ITEM_NAME"]?></td>
<td><?=$row["suggested_qty"]?></td>
<td class="pricetd"><?=$row["Price_item"]?></td>
<td>
<input type="text" name="editedvalues[]" class="qtyinput" value="<?=$row["suggested_qty"]?>" />
</td>
<td><input name='result' class="resultinput" /></td>
</tr>
<?php endwhile?>
</table>
<form>

Return SQL results to clickable table

I am working on a small project. It is a contacts database where users can add and search for contacts. So far you can add contacts and on page load a table populates with results. Great.
But I want to see if its possible to make each row clickable so that when the row is clicked the data is populated using javascript to the form.
One idea I am looking at is when the search results are pulled using a select statement, the id field is also selected and put in a hidden th. Then when the link is clicked the form uses a get method to select the data where the id = what has been selected. Would this work? or is there another way?
For brevity I did not use the include file that handles certain errors.
<!doctype html>
<html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="displayContacts">
<?php
//**********************************************
//*
//* Connect to MySQL and Database
//*
//**********************************************
$db = mysqli_connect('localhost','root','', 'test');
if (!$db)
{
print "<h1>Unable to Connect to MySQL</h1>";
}
include "0811_common_functions_mysqli.php";
$outputDisplay = "";
$myrowcount = 0;
//**********************************************
//*
//* SELECT from table and display Results
//*
//**********************************************
$sql_statement = "SELECT firstname, lastname, pcat, contact_id ";
//, congroup, cattype, company, position, email, website, phone, mphone, wphone, fax, add1, add2, city, state, zip, country, reference, entrydate, enteredby, notes ";
$sql_statement .= "FROM contacts ";
$sql_statement .= "ORDER BY lastname, firstname";
$sqlResults = selectResults($db, $sql_statement);
$error_or_rows = $sqlResults[0];
if (substr($error_or_rows, 0 , 5) == 'ERROR')
{
$outputDisplay .= "<br />Error on DB";
$outputDisplay .= $error_or_rows;
} else {
$arraySize = $error_or_rows;
$outputDisplay .= '<table id="resultstable" style="overflow-x:auto;">';
$outputDisplay .= '<tr><th>Last Name</th><th>First Name</th></tr>';
for ($i=1; $i <= $error_or_rows; $i++)
{
$myrowcount++;
$firstname = $sqlResults[$i]['firstname'];
$lastname = $sqlResults[$i]['lastname'];
$pcat = $sqlResults[$i]['pcat'];
$contactid = $sqlResults[$i]['contact_id'];
$outputDisplay .= "<tr>";
$outputDisplay .= "<td>".$firstname.' '.$lastname."</td>";
$outputDisplay .="<td>".$contactid."</td>";
$outputDisplay .= "<tr>";
$outputDisplay .="<td rowspan=1> $pcat</td>";
$outputDisplay .="</tr>";
$outputDisplay .= "</tr>";
}
$outputDisplay .= "</table>";
}
?>
<?php
$outputDisplay .= "<br /><br /><b>Number of Rows in Results: $myrowcount </b><br /><br />";
print $outputDisplay;
?>
</div>
<div id="main" class="main">
<form action="insert1.php" id="frmBox" method="post" onsubmit="return formSubmit();">
<table style="width:100%">
<tr>
<th>First Name: </th>
<th><input type='text' name='firstname' class="inp" size='20' /></th>
<th>Last Name: </th>
<th><input type='text' name='lastname' class="inp" size='20' /></th>
</tr>
<tr>
<th>Pages Category: </th>
<th><input type='text' name='pcat' class="inp" size='20' /></th>
<th>congroup: </th>
<th><input type='text' name='congroup' class="inp" size='20' /></th>
</tr>
<tr>
<th>Category Type:</th>
<th> <input type='text' name='cattype' class="inp" size='20' /></th>
<th>Company: </th>
<th><input type='text' name='company' class="inp" size='20' /></th>
</tr>
<tr>
<th>Position:</th>
<th><input type='text' name='position' class="inp" size='20' /></th>
</tr>
<tr>
<th>Email:</th>
<th><input type='text' name='email' class="inp" size='20' /> </th>
<th>Website: </th>
<th><input type='text' name='website' class="inp" size='20' /></th>
</tr>
<tr>
<th>H/D Phone: </th>
<th><input type='text' name='phone' class="inp" size='20' /></th>
<th>Mobile Phone: </th>
<th><input type='text' name='mphone' class="inp" size='20' /></th>
</tr>
<tr>
<th>Work Phone: </th>
<th><input type='text' name='wphone' class="inp" size='20' /> </th>
<th>Fax: </th>
<th><input type='text' name='fax' class="inp" size='20' /> </th>
</tr>
<tr>
<th>Address 1: </th>
<th><input type='text' name='add1' class="inp" size='50' /></th>
</tr>
<tr>
<th>Address 2:</th>
<th><input type='text' name='add2' class="inp" size='50' /></th>
</tr>
<tr>
<th>City: </th>
<th><input type='text' name='city' class="inp" size='20' /> </th>
<th>State:</th>
<th><input type='text' name='state' class="inp" size='20' /> </th>
</tr>
<tr>
<th>Zip/Postal Code:</th>
<th><input type='text' name='zip' class="inp" size='20' /></th>
<th>Country:</th>
<th><input type='text' name='country' class="inp" size='20' /></th>
</tr>
<tr>
<th>Reference:</th>
<th><input type='text' name='reference' class="inp" size='20' /></th>
<th>Date Added:</th>
<th> <input type='text' name='entrydate' class="inp" size='20' /></th>
</tr>
<tr>
<th>Entered By: </th>
<th> <input type='text' name='enteredby' class="inp" size='20' /></th>
</tr>
<tr>
<th>Notes:</th>
<th><textarea name="notes" row="10" class="inp" cols="20"></textarea></th>
</tr>
<tr>
<th><input type="submit" name="submit" class="sub-btn" value="Submit"></th>
</tr>
<h3 id="success"></h3>
</table>
</form>
</div>
<div id="results">
</div>
<script src="jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function formSubmit(){
$.ajax({
type:'POST',
url:'insert1.php',
data:$('#frmBox').serialize(),
success:function(response){
$('#success').html(response);
}
});
var form=document.getElementById('frmBox').reset();
return false;
}
function addRowHandlers() {
var table = document.getElementById("resultstable");
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")[1];
var id = cell.innerHTML;
alert("id:" +id);
function formPopulate(id){
$.ajax({
url: "result.php",
success: (function(result){
$("results").html(result);
})
})
}
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
window.onload = addRowHandlers();
</script>
</body>
</html>
Results.php
<!doctype html>
<html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="displayContacts">
<?php
//**********************************************
//*
//* Connect to MySQL and Database
//*
//**********************************************
$db = mysqli_connect('localhost','root','', 'test');
if (!$db)
{
print "<h1>Unable to Connect to MySQL</h1>";
}
include "0811_common_functions_mysqli.php";
$outputDisplay = "";
$myrowcount = 0;
//**********************************************
//*
//* SELECT from table and display Results
//*
//**********************************************
$sql_statement = "SELECT firstname, lastname, pcat, contact_id ";
//, congroup, cattype, company, position, email, website, phone, mphone, wphone, fax, add1, add2, city, state, zip, country, reference, entrydate, enteredby, notes ";
$sql_statement .= "FROM contacts ";
$sql_statement .= "ORDER BY lastname, firstname";
$sqlResults = selectResults($db, $sql_statement);
$error_or_rows = $sqlResults[0];
if (substr($error_or_rows, 0 , 5) == 'ERROR')
{
$outputDisplay .= "<br />Error on DB";
$outputDisplay .= $error_or_rows;
} else {
$arraySize = $error_or_rows;
$outputDisplay .= '<table id="result" style="overflow-x:auto;">';
for ($i=1; $i <= $error_or_rows; $i++)
{
$myrowcount++;
$firstname = test_get($sqlResults[$i]['firstname']);
$lastname = test_get($sqlResults[$i]['lastname']);
$pcat = test_get($sqlResults[$i]['pcat']);
$contactid = $sqlResults[$i]['contact_id'];
$outputDisplay .= "<tr>";
$outputDisplay .= "<td>".$firstname.' '.$lastname."</td>";
$outputDisplay .="<td>".$contactid."</td>";
$outputDisplay .= "<tr>";
$outputDisplay .="<td rowspan=1> $pcat</td>";
$outputDisplay .="</tr>";
$outputDisplay .= "</tr>";
}
$outputDisplay .= "</table>";
mysqli_close($conn);
}
function test_get($data){
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
?>
</div>
</body>
</html>
insert.php
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
<?php
$servername = "localhost";
$username= "root";
$dbpassword = "";
$dbname="test";
$conn=mysqli_connect($servername, $username, $dbpassword, $dbname);
if(!$conn){
die("could not connect:".mysqli_connect_error());
} else{
$firstname=test_input($_POST['firstname']);
$lastname=test_input($_POST['lastname']);
$pcat=test_input($_POST['pcat']);
$congroup=test_input($_POST['congroup']);
$cattype=test_input($_POST['cattype']);
$company=test_input($_POST['company']);
$position=test_input($_POST['position']);
$email=test_input($_POST['email']);
$website=test_input($_POST['website']);
$phone= test_input($_POST['phone']);
$mphone=test_input($_POST['mphone']);
$wphone=test_input($_POST['wphone']);
$fax=test_input($_POST['fax']);
$add1=test_input($_POST['add1']);
$add2=test_input($_POST['add2']);
$city=test_input($_POST['city']);
$state=test_input($_POST['state']);
$zip=test_input($_POST['zip']);
$country=test_input($_POST['country']);
$reference=test_input($_POST['reference']);
$entrydate=test_input($_POST['entrydate']);
$enteredby=test_input($_POST['enteredby']);
$notes=test_input($_POST['notes']);
$sql="INSERT INTO contacts(firstname, lastname, pcat, congroup, cattype, company, position, email, website, phone, mphone, wphone, fax, add1, add2, city, state, zip, country, reference, entrydate, enteredby, notes) ";
$sql .= "values (";
$sql .= "'".$firstname."', '".$lastname."', '".$pcat."', '".$congroup."', '".$cattype."', '".$company."', '".$position."', '".$email."', '".$website."', '".$phone."', '".$mphone."', '".$wphone."', '".$fax."', '".$add1."', '".$add2."', '".$city."', '".$state."', '".$zip."', '".$country."', '".$reference."', '".$entrydate."', '".$enteredby."', '".$notes."'";
$sql .= ")";
if(mysqli_query($conn, $sql)){
echo "Record Inserted";
}else{
echo "insert failed";
}
mysqli_close($conn);
}
function test_input($data){
$data=trim($data);
$data=stripslashes($data);
$data=htmlspecialchars($data);
return $data;
}
?>
</body>
</html>
For the table tr you call a onclick funtion and send an id through it
<tr onClick="formPopulate(id)" >
And when the funtion trigger call a ajax call to retrieve the data and the append to form
in javascript
function formPopulate(id) {
//send an ajax call here to get the data without reloading the page
//after ajax call append the values of ajax response to the form
}

Dynamic table in template written in html/javascript

I try do build a dynamic table, this table should replace a fix table.
<table cellpadding="3" cellspacing="0" border="1">
<tr>
<th>Aufgabe</th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
<th>6</th>
<th>Summe</th>
<th>Note</th>
</tr>
<tr>
<td> </td>
<td><input type="text" id="punkte0" name="punkte0" value="{$punkte.0}" size="3" onKeyUp="aktualisieren('punkte0','punkte1')" /></td>
<td><input type="text" id="punkte1" name="punkte1" value="{$punkte.1}" size="3" onKeyUp="aktualisieren('punkte1','punkte2')" /></td>
<td><input type="text" id="punkte2" name="punkte2" value="{$punkte.2}" size="3" onKeyUp="aktualisieren('punkte2','punkte3')" /></td>
<td><input type="text" id="punkte3" name="punkte3" value="{$punkte.3}" size="3" onKeyUp="aktualisieren('punkte3','punkte4')" /></td>
<td><input type="text" id="punkte4" name="punkte4" value="{$punkte.4}" size="3" onKeyUp="aktualisieren('punkte4','punkte5')" /></td>
<td><input type="text" id="punkte5" name="punkte5" value="{$punkte.5}" size="3" onKeyUp="aktualisieren('punkte5','punkte6')" /></td>
<td id="tds1">0</td>
<td></td>
</tr>
<tr>
<td>Gesamt</td>
<td colspan="6"></td>
<td id="summe">0</td>
<td id="note">{$student.note/10}</td>
</tr>
</table>
But the columns should be user-dependent, so I wrote a function in my PHP code, which save the value (number between 4 an 7) in my database. It is called in the database klausuraufgaben.
I tried this to replace the columns:
$iQuantity = (integer)$_POST['klausuraufgaben'];
$aTableHeads = [];
$aTableContents = [];
for ( $x=0; $x<$iQuantity; $x++ ) {
$aTableHeads[] = '<th>' . ($x + 1) . '</th>';
$aTableContents[] = '<td><input type="text" id="punkte' . (string)$x . '" name="punkte' . (string)$x . '" value="{$punkte.' . (string)$x . '}" size="3" onKeyUp="aktualisieren('punkte. (string)$x . '",'punkte. (string)$x+1 . '"></td>';
But it doesn't work. Can someone see what is wrong?
This is the Error, which I get:
[in kartei.tpl line 254]: syntax error: unrecognized tag: $aTableHeads[] = '' . ($x + 1) . ''; $aTableContents[] = '
thanks, i edit the code for the template in this way:
{php}
$iQuantity = (integer)$_POST['klausur_aufgaben'];
$aTableHeads = [];
$aTableContents = [];
{for $x=0 to $iQuantity;}
// {for( $x=0; $x<$iQuantity; $x++ )
$aTableHeads[] = '<th>' . ($x + 1) . '</th>';
$aTableContents[] = '<td><input type="text" id="punkte' . (string)$x . '" name="punkte' . (string)$x . '" value="{$punkte.' . (string)$x . '}" size="3" onKeyUp="aktualisieren('punkte. (string)$x . '",'punkte. (string)$x+1 . '"></td>';
{/for}
{/php}
I'm not smarty expert, but lets have a crack at this.
{php}
$iQuantity = (integer)$_POST['klausur_aufgaben'];
{/php}
<tr>
{for $x=0 to $iQuantity}
<th>{$x + 1}</th>
{/for}
</tr>
{for $x=0 to $iQuantity}
<td><input type="text" id="punkte{$x}" name="punkte{$x}" value="NotSureHere this needs to come from another array?" size="3" onKeyUp="aktualisieren('punkte{$x}','punkte{$x+1}')"/></td>
{/for}

Replace img scr on click and not require page refresh. Ajax Jquery Javascript Php MySql

I have the following 2 php scripts. booking.php is created on the fly doing a call to a mysql database and returning results into the tables. To make this a somewhat simple example and only am showing a few fields...actually table has 54 fields in them.
The idea behind this is every table is a Customer order. The openbutton or closebutton is a image representing what status the order is in. If it is closed the closedbutton image appears. If the order is opened then the openbutton image appears. when I click on the
Everything work (process wise), however, the image only allows me to click it once per table and requires me to refresh the page to click on it again.
What is want is to be able to click the openbutton/closedbutton image on a table as many times as I want and have the correct image appear after I click it and the mysql table has processed it.
booking.php
<?php
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function(){
$('.status_button').click(function(){
var element = $(this);
var I = element.attr('id');
var id=$('#id'+I).val();
var sname = $(this).attr('title');
$.post('openclose.php', {id: id, sname: sname},
function(data){
var response = (data).split(';',2);
$('#messageA'+I).html(response[0]);
$('#messageA'+I).hide();
$('#messageA'+I).fadeIn(1500);
$('#messageB'+I).html(response[1]);
$('#messageB'+I).hide();
$('#messageB'+I).fadeIn(1500);
});
return false
;})
;});
</script>
<style type='text/css'>
table {border: 1px solid black}
td, tr {border: 0}
</style>
</head>
<body>
<table>
<th>Id</th>
<th>Year</th>
<th>First Name</th>
<th>Last Name</th>
<th>Actions</th>
<tr>
<td><input type='text' id='id1' size='3' readonly='readonly' value='1'></td>
<td><input type='text' id='year1' size='2' value='2013'></td>
<td><input type='text' id='fname1' size='10' value='Brian'></td>
<td><input type='text' id='lname1' size='15'value='Smith'></td>
<td><div id='messageB1'><a id='1', href='#' class = 'status_button' title='Close1'> </div>
<div id='messageA1'><img src='images/openbutton.jpg', title='Order Status' border='0' height='24' width='24'></img></div></a></td>
</tr>
</table>
<table>
<th>Id</th>
<th>Year</th>
<th>First Name</th>
<th>Last Name</th>
<th>Actions</th>
<tr>
<td><input type='text' id='id2' size='3' readonly='readonly' value='2'></td>
<td><input type='text' id='year2' size='2' value='2014'></td>
<td><input type='text' id='fname2' size='10' value='Kurt'></td>
<td><input type='text' id='lname2' size='15'value='Jones'></td>
<td><div id='messageB2'><a id='2', href='#' class = 'status_button' title='Open2'> </div>
<div id='messageA2'><img src='images/closebutton.jpg', title='Order Status' border='0' height='24' width='24'></img></div></a></td>
</tr>
</table>
<table>
<th>Id</th>
<th>Year</th>
<th>First Name</th>
<th>Last Name</th>
<th>Actions</th>
<tr>
<td><input type='text' id='id3' size='3' readonly='readonly' value='2'></td>
<td><input type='text' id='year3' size='2' value='2014'></td>
<td><input type='text' id='fname3' size='10' value='Ryan'></td>
<td><input type='text' id='lname3' size='15'value='Davis'></td>
<td><div id='messageB3'><a id='3', href='#' class = 'status_button' title='Open3'></div>
<div id='messageA3'><img src='images/openbutton.jpg', title='Order Status' border='0' height='24' width='24'></img></div></a></td>
</tr>
</table>
</body>
?>
openclose.php
<?php
include('connection.php');
$id=$_POST['id'];
$sname=$_POST['sname'];
$rest = substr($sname, 0, -1);
if ($rest == "Open")
$change="O";
else
$change="C";
$query = "UPDATE info SET status_ = '$change' WHERE id = $id";
$result = mysql_query($query) or die ( mysql_error ());
if ($change == "O")
$image ="<img src='images/openbutton.jpg', title='Order Status' border='0' height='24' width='24'></img>";
else
$image="<img src='images/closebutton.jpg', title='Order Status' border='0' height='24' width='24'></img>";
if ($rest == "Close")
$status_change ="<a id='$id', href='#' class = 'status_button' title='Open'>";
else
$status_change= "<a id='$id', href='#' class = 'status_button' title='Close'>";
echo "$image;$status_change";
?>
$('.status_button').click(function(){
should be:
$(document).on('click', '.status_button', function(){
http://api.jquery.com/on/
And...
echo "$image;$status_change";
go to:
echo $image.";".$status_change.";";
make openbutton & closebutton changes in the first page
like this
<div id='message'><img src='images/closebutton.jpg' id='message' title='Order Status' border='0' height='24' width='24'></img></div>
<script>
$('img#message').click(function(){
var messageimage;
messageimage = $('img#message').attr();
if(messageimage == 'images/closebutton.jpg'){
$('img#message').attr('src','images/openbutton.jpg');
}else{
$('img#message').attr('src','images/closebutton.jpg');
}
});
</script>

Categories