I have a html table the gets its values from a postgres table,have used php to echo the table content.
There are n no of rows in my table, When I click on the row I want the values of that row to be used in another function,
My code to populate the table with sql values is
while($row1 = pg_fetch_assoc($result1)) {
echo "<tr>"
. "<td>{$row1['name']}</td>"
. "<td>{$row1['email']}</td>"
. "<td>"
. "<form id='form_id'>"
. "<input type='hidden' id='cord' value=$row1['lat']>"
. "<input type='hidden' id='cord1' value=$row1['lon']>"
. "<a onclick='submit_by_id()' >view</a>"
. "</form>"
. "</td>"
. "</tr>\n";
}
}
?>
The html table is displayed, But only the first row values are shown (in the alert box) when I click the onclick function , I don't know how to reset the form values on click or is there any other way to optimize it.
function submit_by_id() {
var geom=document.getElementById('cord').value;
var geom1=document.getElementById('cord1').value;
alert(geom);
alert(geom1);
}
<table>
<thead>
<tr>
<th>Name</a</th>
<th>Email</th>
<th>Click to view</th>
</tr>
</thead>
<tbody>
<tr>
<td>name1</td>
<td>email1</td>
<td>
<form id='form_id'>
<input type='hidden' id='cord' value=15><input type='hidden' id='cord1' value=73><a onclick='submit_by_id()' >view</a>
</form>
</td>
</tr>
<tr>
<td>name2</td>
<td>email2</td>
<td>
<form id='form_id'>
<input type='hidden' id='cord' value=16><input type='hidden' id='cord1' value=78><a onclick='submit_by_id()'>view</a>
</form>
</td>
</tr>
</tbody>
</table>
</div>
You are iterating using while loop, but it does not create dynamic form in each iteration. which means all form in row a same. and submit form does not specify which form to sumit. you can do something like this
while($row1 = pg_fetch_assoc($result1)) {
$i=0;
echo "<tr>"
. "<td>{$row1['name']}</td>"
. "<td>{$row1['email']}</td>"
. "<td>{$row1['device_id']}</td>"
. "<td>{$row1['last_login']}</td>"
. "<td>"
. "<form id='form_id"$i."'>"
. "<input type='hidden' id='cord".$i."' value=$latlon[0]>"
. "<input type='hidden' id='cord1".$i."' value=$latlon[1]>"
. "<a onclick='submit_by_id($i)' >view</a>"
. "</form>"
. "</td>"
. "</tr>\n";
$i++;
}
}
?>
in javascript
function submit_by_id(id) {
var geom=document.getElementById('cord'+id).value;
var geom1=document.getElementById('cord1'+id).value;
alert(geom);
alert(geom1);
}
when you are using multiple rows, your id cord1 and cord also repeating. make it dynamically vary to each row or use class to get the value.
Well as the tags indicate jQuery is allowed so i use jQuery.
You should not have multiple elements with the same id. Use a class instead:
. "<form id='form_id'>"
. "<input type='hidden' class='cord' value=$latlon[0]>"
. "<input type='hidden' class='cord1' value=$latlon[1]>"
. "<a onclick='submit_by_id()' class='glyphicon glyphicon-pushpin'></a>"
. "</form>"
To access it a nice way is to use closest to find the form the element is in:
function submit_by_id() {
var $form = $(this).closest('form');
var geom= $form.find('.cord').val();
var geom1= $form.find('.cord1').val();
alert(geom);
alert(geom1);
}
ID should be unique, you need to use class in your case.
Change
id='cord' and id='cord1'
to
class='cord' and class='cord1'
And your JS code
function submit_by_id() {
var geom=document.getElementById('cord').value;
var geom1=document.getElementById('cord1').value;
alert(geom);
alert(geom1);
}
to
function submit_by_id() {
var $form = $(this).parent();
var geom= $form.find('.cord').val();
var geom1= $form.find('.cord1').val();
alert(geom);
alert(geom1);
}
Related
I have this PHP code and I am trying to alert a table that receives its values via sql.
Here's my code:
<script src="jquery.min.js">
</script>
<script>
function bus(x){
alert("Row index is: " + x.value);
}
</script>
$sql="SELECT ID, NOME, CPF FROM cadastro WHERE NOME LIKE '%" . $name . "%'";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($result)){
$ID =$row['ID'];
$NOME=$row['NOME'];
$CPF=$row['CPF'];
echo '<table style="width:100%">';
echo "<tr>";
echo "<th> ID </th>";
echo "<th> NOME </th>";
echo "<th> CPF </th>";
echo "</tr>";
echo '<tr style="cursor: pointer;">';
echo "<td onclick='bus(" . $ID . ")' class='tab'>" . $ID . "</td>";
echo "<td onclick='bus(" . $ID . ")' class='tab'>" . $NOME . "</td>";
echo "<td onclick='bus(" . $ID . )' class='tab'>" . $CPF . "</td>";
echo "</tr>";
echo "</table>";
I need to get the value from the table and serve it to a javascript function.
If x is a Number, then x.value will give you undefined and you should just use:
alert("Row index is: " + x);
To get the value of the column, you could pass this to the function instead of the id and then get the innerHTML:
<td onclick="bus(this)" class="tab">column 1</td>
function bus(elm){
alert(elm.innerHTML);
}
function bus(elm) {
alert(elm.innerHTML);
}
<table>
<tr>
<td onclick="bus(this)" class="tab">column 1</td>
<td onclick="bus(this)" class="tab">column 2</td>
<td onclick="bus(this)" class="tab">column 3</td>
</tr>
</table>
You only have one error. onclick is passing the ID, so the following code will do exactly what you need:
<script>
function bus(x){
alert("Row index is: " + x);
}
</script>
I removed the .value from your javascript.
function bus(x){
alert("Value is " + x);
}
<table>
<tr>
<td onclick="bus(44)">44</td>
<td onclick="bus(44)">Lorem</td>
<td onclick="bus(44)">ipsum</td>
</tr>
</table>
In this case x is not an object, just a plain value so:
alert("Row index is: " + x);
gl, pb
I have a while loop that displays some data into a table from a mysql table. Each table row has a button that is used to send data via ajax to another php page that insert the data into another table. My problem is that I want to get the values of specific rows by getting their ids but because I'm outside of the loop, I'm not able to the $row variable... How can I do such a thing?
Here is the portion of the code:
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['TROUBLE_TICKET_NUM'] . "<input type=\"hidden\" name=\"billet".$row['TROUBLE_TICKET_NUM']."\" id=\"billet".$row['TROUBLE_TICKET_NUM']."\" value=\"".$row['TROUBLE_TICKET_NUM']."\"></td>";
echo "<td>" . $row['CONCAT(Year(activites.ACTIVITY_CREATE_DTM),month(activites.ACTIVITY_CREATE_DTM))'] . "</td>";
echo "<td>" . $row['CUSTOMER_NM'] . "</td>";
echo "<td>" . $row['DEFAULT_WORK_GROUP_CD'] . "</td>";
echo "<td>" . $row['ACTIVITY_OWNER_NM'] . "<input type=\"hidden\" name=\"id".$row['TROUBLE_TICKET_NUM']."\" id=\"id".$row['TROUBLE_TICKET_NUM']."\" value=\"".$row['ACTIVITY_OWNER_NM']."\"></td>";
echo "<td>" . $row['groupe'] . "</td>";
echo "<td>" . $row['Technicien'] . "<input type=\"hidden\" name=\"technicien".$row['TROUBLE_TICKET_NUM']."\" id=\"technicien".$row['TROUBLE_TICKET_NUM']."\" value=\"".$row['Technicien']."\"></td>";
echo "<td>
<label for=\"date". $row['TROUBLE_TICKET_NUM'] ."\"><strong>Date:</strong></label>
<input type=\"text\" name=\"date". $row['TROUBLE_TICKET_NUM'] ."\" id=\"date". $row['TROUBLE_TICKET_NUM'] ."\" onClick=\"ds_sh(this);\" value=\"".date("Y-m-d")."\">
<label for=\"heure". $row['TROUBLE_TICKET_NUM'] ."\"><strong>Heure:</strong></label>
<input type=\"text\" class=\"timepicker\" name=\"heure". $row['TROUBLE_TICKET_NUM'] ."\" id=\"heure". $row['TROUBLE_TICKET_NUM'] ."\"></td>
<td><button type=\"button\" class=\"btn btn-success btn-block\" name=\"insert-data". $row['TROUBLE_TICKET_NUM'] ."\" id=\"insert-data". $row['TROUBLE_TICKET_NUM'] ."\" onclick=\"insertData()\">Ajouter suivi</button>
<br>
<p id=\"message\"></p>
</td>";
echo "<tr>";
}
} else {
echo "<tr><td><div class=\"alert alert-dark\" role=\"alert\">Aucun résultat</div></td></tr>";
}
mysqli_close($conn);
?>
</tbody>
</table>
</div>
<!-- Script pour envoi donnée via ajax -->
<script type="text/javascript">
$(document).ready(function(){
$("#insert-data<?php echo $row['TROUBLE_TICKET_NUM']; ?>").click(function(){
var billet=$("#billet<?php echo $row['TROUBLE_TICKET_NUM']; ?>").val();
var technicien=$("#technicien<?php echo $row['TROUBLE_TICKET_NUM']; ?>").val();
var id=$("#id<?php echo $row['TROUBLE_TICKET_NUM']; ?>").val();
var date=$("#date<?php echo $row['TROUBLE_TICKET_NUM']; ?>").val();
var heure=$("#heure<?php echo $row['TROUBLE_TICKET_NUM']; ?>").val();
// Debug
console.log(billet, technicien, tid, date, heure);
// AJAX
$.ajax({
method: "POST",
url: "insert-data.php",
data: {billet:billet,technicien:technicien,id:id,date:date,heure:heure},
dataType: "JSON",
success: function(data) {
$(".message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
});
});
</script>
If your intent is to allow the user to only insert values that come from existing rows, then don't pass the values you want to insert to the AJAX target. Otherwise, the user could manually call the AJAX target and simply provide any values they want. Instead, send the ID of the source row, and update the AJAX target to lookup that row and then copy the values from it.
You can do this by putting the row id into a data attribute for each row:
<tr data-id="<?= $row['id'] ?>">
Then use a jquery selector that fires on click of the button to get that value for the clicked row. Something like:
$(this).parent().data('id')
My question might be confusing, basically I have two tables in my ordering, one which is connected to a mysql database displaying the items i have in stock and the other (empty) table is where all my selected items go.
pic: http://tinypic.com/r/o89pn5/8
Now, everytime i click the button beside each row on the top table, it transfers the rows to the lower table
pic: http://tinypic.com/view.php?pic=290sfw2&s=8#.U7LMjpSSzTo
Now notice on the lower table I have another column named "Quantity". Can anyone show me how to fill this column with textboxes? Thanks a lot to anyone who can help me. I'm just staring to learn Javascript/JQuery.
Please feel free to ask me more questions in case my question is not clear.
Code for the tables:
<!-- Table 1(inventory table) -->
<?php
$con=mysqli_connect("localhost","root","","purchasing");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM tbl_inventory");
echo "<table id='table1' class='inventory' border='3'>
<tr>
<th>Check</th>
<th>ID</th>
<th>Product Name</th>
<th>Price</th>
<th>Stock</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td> <button class='btn'>order</button> </td>";
echo "<td>" . $row['prod_id'] . "</td>";
echo "<td>" . $row['prod_name'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td>" . $row['stock'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
<br/><br/>
<!-- Table 2(ordered items table) -->
<table id="table2" class="inventory" border="3">
<tr>
<th>Check</th>
<th>ID</th>
<th>Product Name</th>
<th>Price</th>
<th>Stock</th>
<th>Quantity</th>
</tr>
<tbody>
</tbody>
</table>
The scripts:
<script>
$(".btn").click(function () {
// get the row containing this link
var row = $(this).closest("tr");
// find out in which table it resides
var table = $(this).closest("table");
// move it
row.detach();
if (table.is("#table1")) {
$("#table2").append(row);
}
else {
$("#table1").append(row);
}
// draw the user's attention to it
row.fadeOut();
row.fadeIn();
});
</script>
After this line:
$("#table2").append(row);
just append textbox in last tr last td like this:
$("#table2").find("tr:last").find("td:last").append('<input type="text" class="quantity" />');
JQuery gives you a few different ways to dynamically add elements to the page. In this case, if you wanted to add a text input to a td element you could do something simple like this:
<script>
$('table#table2 td.quantity').append('<input type="text" name="quantity" id="quantity" value="0" />");
</script>
You can also build elements using various JQuery methods and then append the the JQuery object directly:
<script>
var inputObj = $('<input />');
inputObj.attr('type','text').val('0').attr('name','quantity').attr('id','quantity');
$('table#table2 td.quantity').append( inputObj );
</script>
Hopefully, this may work, but it won't remember whichever value has been put in the text box if a user removes the row from #table2 and put it back later on.
if (table.is("#table1")) {
row.append('<td><input type="text" class="quantity" /></td>');
$("#table2").append(row);
}
else {
row.find('td:last').remove();
$("#table1").append(row);
}
If you have good html5 support, you should be able to use inputs of type number instead of a plain text box.
As an extra, you probably want to have the fadeout/fadein happen around the row move. You may implement it as follow:
var row = $(this).closest('tr');
var table = $(this).closest('table');
row.fadOut(300, function(){
row.detach();
if (table.is("#table1")) {
row.append('<td><input type="text" class="quantity" /></td>');
row.find('.btn').html('remove');
$("#table2").append(row);
}
else {
row.find('td:last').remove();
row.find('.btn').html('order');
$("#table1").append(row);
}
row.fadeIn(300);
});
I have the following block of code and I'm not sure how to do what I'm wanting to do.
In essence I'm wanting the javascript popup to display that row's value, but (obviously) it's only showing the final row of data as the popup isn't set for each row but rather calls the variable when clicked.
Any help would be appreciated!
<?php
$result = mysql_query("SELECT hr_overtime.overtime_id, hr_user.name, hr_overtime.overtime_date, hr_overtime.overtime_type, hr_overtime.overtime_from, hr_overtime.overtime_to, hr_overtime.overtime_amount, hr_overtime.details
FROM hr_overtime
inner join hr_user
on hr_user.user_id = hr_overtime.user_id
where hr_overtime.overtime_status = 'Pending' order by hr_overtime.overtime_date ASC");
echo "
<table border='0'>
<tr>
<th class='tablecell_header'>Consultant</th>
<th class='tablecell_header'>Date</th>
<th class='tablecell_header'>Type</th>
<th class='tablecell_header'>From</th>
<th class='tablecell_header'>To</th>
<th class='tablecell_header'>Amount</th>
<th> </th>
<th> </th>
<th> </th>
</tr>";
while($row = mysql_fetch_array($result))
{
$work = $row['details'];
echo "<tr>";
echo "<td class='tablecell'>" . $row['name'] . "</td>";
echo "<td class='tablecell'>" . $row['overtime_date'] . "</td>";
echo "<td class='tablecell'>" . $row['overtime_type'] . "</td>";
echo "<td class='tablecell'>" . $row['overtime_from'] . "</td>";
echo "<td class='tablecell'>" . $row['overtime_to'] . "</td>";
echo "<td class='tablecell'>" . $row['overtime_amount'] . "</td>";?>
<td class='tablecell'> <button onclick="myFunction()">Show work</button> </td><script>
function myFunction()
{
alert("<?php echo $work;?>");
}
</script>
<?php
echo "<td valign='middle'><form action='manager_overtime_approve.php' method='post'>
<input name='approve_id' type='hidden' value='" . $row['overtime_id'] . "' />
<input type='submit' value='APPROVE' id='edit' />
</form></td>";
echo "<td valign='middle'><form action='manager_overtime_reject.php' method='post'>
<input name='cancel_id' type='hidden' value='" . $row['overtime_id'] . "' />
<input type='submit' value='REJECT' id='edit' />
</form></td>";
echo "</tr>";
}
echo "</table>";
?>
There is no need for a separate function which you are using incorrectly. You can simply use an inline alert for this:
<td class='tablecell'> <button onclick="alert('<?php echo $work;?>');">Show work</button>
You can't insert the declaration of myFunction() inside your foreach loop, that way you are overriding for each entry the behaviour showed thus it's only working for the last row.
one fast solution would be to insert the whole $work variable as an argument of your onclick function eg.
<td class='tablecell'> <button onclick="myFunction('<?php echo $work ?>')">Show work</button>
and then outside of the foreach loop you can define myFunction such as:
function myFunction(details){
alert(details)
}
I think, in result HTML you have a multiple definitions of myFunction() and javascript uses only last one. You can use a HTML tag attributes to show right information.
try this
$work .= $row['details'];
and set javascript out of the loop
good luck
That's because myFunction is a Javascript function, which is defined once and doesn not share the same scope as PHP. So $work hold just the last value.
I'd suggest something like this:
echo "<tr data-detail-value='$work'>";
...
<td class='tablecell'> <button onclick="myFunction(this)">Show work</button>
...
function myFunction(btn) {
alert(btn.parentNode.parentNode.getAttribute("data-detail-value"));
}
I am currently building an internal tool for viewing and editing SQL-like tables via the web. I have some PHP and html written that generates these tables and jQuery written that does this, so far:
Delete Rows
Add New Rows
Output form value after entry
The ultimate goal, of course, is to generate a SQL statement using INSERT, UPDATE, DELETE, etc on the modified data. I have a grasp on how to concatenate the results into such a statement, but could use help targeting columns for it.
My main concern is modifying the form value output function so that I can store any updated entries in an array and output them as a CSV string. I've read about .each, .map, .push, and .serializeArray. I'm not sure exactly how to use/combine these methods to accomplish the desired result. Here are some code snippets:
The current jQuery:
$('#add_row').on('click', function(){
$('<tr><td id="data"><input class ="new_row"></td><td id="data"><input class ="new_row"></td><td id="data" style="text-align:center;"><input class ="new_row"></td><td id = "Delete_Button"><button class="rmv_row">-</button></td></tr>').appendTo('#SQLdata');
});
$("table").on('keyup', 'input', function(){
$('#output').text($(this).val());
});
$('table').on('click', '.rmv_row', function(){
$(this).closest('tr').remove();
});
});
and the PHP/HTML:
<table id="SQLdata">
<tr style="background-color: margin-left:#6b685c;">
<td style="background-color: margin-left:#6b685c; font-family:tahoma,arial,verdana,sans-serif"; colspan="3">
<form style="color:black;" method="post" action="WebEventsStructureColumnTool.php">
Select your table name:
<select method="post" name="table_name" id="picker">
<option>Removed For Security</option>
</select>
<input type="submit" value="Go" name="submit">
</form>
</td>
<td><button id="add_row">Add a Row</button></td>
</tr>
$tableName = $_POST['table_name'];
$statementObject = $pdo->prepare("SELECT a, b, c FROM tab WHERE _id =?");
$statementObject->bindParam(1, $tableName, PDO::PARAM_STR);
$statementObject->execute();
$statementObject->bindColumn('a', $Col1);
$statementObject->bindColumn('b', $Col2);
$statementObject->bindColumn('c', $Col3);
while ($statementObject->fetchAll(PDO::FETCH_BOUND)){
// Gets an array from the CSVs in the column :
$Column1 = explode(",", $Col1);
$Column2 = explode(",", $Col2);
$Column3 = explode(",", $Col3);
}
//Fetches the total number of values from each exploded array:
$Count1 = count($Column1);
$Count2 = count($Column2);
$Count3 = count($Column3);
//Establishes the total length/height of the table:
$largest = $Count1;
if ($Count2 > $largest){
$largest = $Count2;
}
if ($Count3 > $largest){
$largest = $Count3;
}
echo '
<tr>
<th>a</th>
<th>b</th>
<th style="text-align: center">c</th>
<th>delete row</th>
</tr>';
for($i = 0; $i < $largest; $i++){
$tableRows[] =
"<tr>
<td id='data'>
<input type='text' value='" . $Column1[$i] . "'>
</td>" .
"<td id='data'>
<input type='text' value='" . $Column2[$i] . "'>
</td>" .
"<td id = 'data' style='text-align:center;'>
<input type='text' value='". $Column3[$i]. "'>
</td>
<td id = 'Delete_Button'><button class='rmv_row'>-</button></td>";
}
foreach ($tableRows as $row){
echo $row;
}
echo '</table><div><table><tr id="output" colspan="4"></tr></table>'
If anyone also has advice/recommendations on existing code, feel free to criticize. I am a young developer just starting out and could use all the help I can get. Thanks!
I added this bit this morning and am now successfully getting CSVs:
var string = new Array()
function updateString(){$('#output').text(string);}
$('input').each(function(){
string.push($(this).val());
});
Working on creating three different arrays for each data manipulation option and limiting printing to conditionals.