I am a newbie in Jquery. I have a table in my webpage which shows the contents of a user table from the database.I have also created an edit button and Delete button for each row of data.I need the id of each edit and delete button for writing code for editing and deleting the records in the database as well as implementing this changes in the table in the webpage also.
$query = mysqli_query($con,"SELECT * FROM user_details");
while($row = mysqli_fetch_array($query))
{
echo "<tr>";
echo "<td>".$row['fname']."</td>";
echo "<td>".$row['mname']."</td>";
echo "<td>".$row['childname']."</td>";
echo "<td><input type='button' id = 'edit".$row['Id']."' value='Edit'></td>";
echo "<td><input type='button' id = 'delete".$row['Id']."' value='Delete'></td>";
echo "</tr>";
}
If I am using Jquery,how to get the IDof each button?Or If I write a onclick event using javascript for each button and passes the ID's as arguments,can I access via Jquery.Please help me
$("button").each(function(index, item) {
var itemId = $(item).attr('id');
});
But I would set the $row['id'] into a data-id attribute and then use:
$("button").each(function(index, item) {
var itemId = $(item).data('id');
});
Add common class name and use that as a selector to get id of the buttons like below
Try like this
$(document).on('click','.edit_btn',function(){
alert($(this).attr('id'));
});
$(document).on('click','.del_btn',function(){
alert($(this).attr('id'));
});
HTML
<input type='button' id ='edit' class="edit_btn" value='Edit'>
<input type='button' id ='delete' class="del_btn" value='Delete'>
DEMO
First of all, you need to escape your variables in HTML context using htmlspecialchars(). Second, you can use data attributes to easily identify the record that needs be edited or deleted.
?>
<tr>
<td><?= htmlspecialchars($row['fname'], ENT_QUOTES, 'UTF-8') ?></td>
<td><?= htmlspecialchars($row['mname'], ENT_QUOTES, 'UTF-8') ?></td>
<td><?= htmlspecialchars($row['childname'], ENT_QUOTES, 'UTF-8') ?></td>
<td><input type="button" class="edit" data-id="<?= $row['Id'] ?>" value="Edit"></td>
<td><input type="button" class="delete" data-id="<?= $row['Id'] ?>" value="Delete"></td>
</tr>
<?php
Then, you can use classes to identify the buttons instead:
$('.edit').on('click', function() {
var id = $(this).data('id');
// edit stuff
});
$('.delete').on('click', function() {
var id = $(this).data('id');
// delete stuff
});
You can use a data-* attribute to specify the ID and use a common class to call the click handler
echo "<td><input type='button' id = 'edit".$row['Id']."' data-id='".$row['Id']."' value='Edit' class='edit-record'></td>";
then in jQuery
jQuery(function ($) {
$(document).on('click', '.edit-record', function () {
//this is called when the edit button is clicked
var $this = $(this),
id = $this.data('id');
//now id has the value of current record's id
})
})
Use Attribute starts with selector, and Event Delegation
$(document).on("click" , "[id^='edit']" ,function() {
console.log(this.id);
});
$(document).on("click" , "[id^='delete']" , function() {
console.log(this.id);
});
Related
I have problem with $(this).nextAll("#status").eq(0).text("Deleted").
I want to in the tag <span> put a text: "Deleted", but but does not insert it...
See the my code:
admin.php PHP:
$sql = "SELECT * FROM `upload_img`";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo "<div class='image' data-id='".$row['id']."'><br>";
echo "<span><strong>Image title</strong>: ".$row['image_title']."</span><br>";
echo "<span><strong>User of image</strong>: ".$row['user_name']."</span><br>";
echo "<span><strong>Image file name</strong>: ".$row['image']."</span><br>";
echo "<span id='status'></span>";
echo "<button class='delete' data-id='".$row['id']."'>Delete</button><hr>";
echo "</div>";
}
admin.js JS:
$(".delete").on("click", function() {
var id = $(this).data("id");
$(this).nextAll("#status").eq(0).text("Deleted"); //This is not work!
$.post("adminServer.php", { id: id }, function(data) {
data = JSON.parse(data);
alert(data);
});
});
I do not know why it does not work...
Thanks!
Firstly part of your problem is that id attributes must be unique within the DOM. As such, only the first one will be recognised. You need to change the HTML generated to use a class on the status element instead:
$sql = "SELECT * FROM `upload_img`";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_assoc($result)) {
echo '<div class="image" data-id="'.$row['id'].'"><br>';
echo '<span><strong>Image title</strong>: '.$row['image_title'].'</span><br>';
echo '<span><strong>User of image</strong>: '.$row['user_name'].'</span><br>';
echo '<span><strong>Image file name</strong>: '.$row['image'].'</span><br>';
echo '<span class="status"></span>'; // change the id to class here
echo '<button class="delete" data-id="'.$row['id'].'">Delete</button><hr>';
echo '</div>';
}
Secondly your DOM traversal logic isn't quite right. nextAll() goes through successive siblings, yet the status you're looking for is a preceding sibling. You can either use prev() or get the closest() parent, then find() within that. The latter is far more robust should you ever change the order of HTML elements. Also note that eq(0) is redundant as there's only one status generated per .image container.
$(".delete").on("click", function() {
var id = $(this).data("id");
$(this).closest('div.image').find('.status').text("Deleted");
$.post("adminServer.php", { id: id }, function(data) {
data = JSON.parse(data);
console.log(data); // don't use alert() for debugging.
});
});
Check below code with sample data. Hope it helps.
$(this).siblings(".status").eq(0).text("Deleted");
It gets nearby sibling with id status and update with status "Deleted"
$(".delete").on("click", function() {
var id = $(this).data("id");
$(this).siblings(".status").eq(0).text("Deleted");
/*
$.post("adminServer.php", { id: id }, function(data) {
data = JSON.parse(data);
console.log(data); // don't use alert() for debugging.
});
*/
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='image' data-id='1'>
<br>
<span><strong>Image title</strong>: Test1</span><br>
<span><strong>User of image</strong>: Test1</span><br>
<span><strong>Image file name</strong>: Test1</span><br>
<span class='status'></span>
<button class='delete' data-id='1'>Delete</button><hr>
</div>
<div class='image' data-id='2'>
<br>
<span><strong>Image title</strong>: Test2</span><br>
<span><strong>User of image</strong>: Test2</span><br>
<span><strong>Image file name</strong>: Test2</span><br>
<span class='status'></span>
<button class='delete' data-id='2'>Delete</button><hr>
</div>
<div class='image' data-id='3'>
<br>
<span><strong>Image title</strong>: Test3</span><br>
<span><strong>User of image</strong>: Test3</span><br>
<span><strong>Image file name</strong>: Test3</span><br>
<span class='status'></span>
<button class='delete' data-id='3'>Delete</button><hr>
</div>
In my html-php table:
<tr id="idrow">
<td><?php echo $user_id; ?></td>
<td ><?php echo $user_name; ?></td>
<td>
<input type="button" class="btn btn-danger btn-xs delete " value="Cancella sin id" onclick="deleteFunction(<?php echo $user_id; ?>)"/>
</td>
</tr>
there is a button to erase sql row by a ajax call, using the id field.
My problem is on update table after success:
my js code is:
function deleteFunction(valor) {
var $tr = $('#datatable-id').closest('tr');
var id = valor;
var parametros = {
"id" : id
};
console.log(parametros);
$.ajax({
type: "POST",
url: "deleteTabla.php",
data: parametros,
success: function(result){
//$("#idrow").remove();
$tr.remove();
},
error: function () {
console.log('ajax error');
}
});
}
Using $("#idrow").remove(), the first row is removed, not the button related one.
I suppose the trick is on var $tr = $('#datatable-id').closest('tr');, the reference to tr label?
Any help is appreciated.
If I understand correctly, every row has the same id (idrow). This is your first mistake. Ids have to be unique throughout the whole page. Create the rows with a unique Id and pass it to the function:
<tr id="idrow_<?php echo $user_id; ?>">
...
<td>
<input type="button" onclick="deleteFunction('<?php echo $user_id; ?>')"/>
</td>
</tr>
In your function, just do this:
function deleteFunction(valor) {
...
$('#idrow_'+valor).remove();
...
}
The closest tr to the #datatable-id will always be the first row.
If you want to delete a particular row try assigning an id.
<tr id="<?php echo $user_id;?>">
....
</tr>
Then in the function:
function deleteFunction(valor) {
var $tr = $('#' + valor);
// delete after request is success
$tr.remove()
}
Try this
<tr id="idrow_<?= $user_id ?>">
And on success:
$("#idrow_" + valor).remove();
Change your selector at the beginning of the function to this: var $try = $("#idrow")
So, I have a table emitting data from database table.
//Display the simplex table
echo "<div id='simptable'>";
$sqlGet = "SELECT * FROM simplex_list";
//Grab data from database
$sqlSimplex = mysqli_query($connect , $sqlGet)or die("Error retrieving data!");
//Loop to display all records on webpage in a table
echo "<table>";
echo "<tr><th>Product Code</th><th>Description</th><th>Quantity</th></tr>";
while ($row = mysqli_fetch_array($sqlSimplex , MYSQLI_ASSOC)) {
echo "<tr><td>";
echo "<input type='text' id='sim' value='".$row['s_code']."' readonly>";
echo "</td><td>";
echo $row['description'];
echo "</td>";
echo "<input type='hidden' id='com' name='complexcode' value='$newProductID'>";
echo "<td>";
echo "<input type='text' size='7' id='userqty'>";
echo "</td><td>";
echo "<input type='button' onclick='addthis()' value='Add!'>";
echo "</td></tr>";
}
echo "</table>";
echo "</div>";
And I try to alert the 'Product Code' here when the user clicks 'Add' button....
function addthis() {
var scode = $('#sim').val();
alert(scode);
}
The problem is it only alerts the first Product Code in the table. That from row 1.
Example:
Product code Name More
123 Toy 'Add'
321 Food 'Add'
555 Pen 'Add'
So if I click on 'Add' for food or pen it will still alert 123..
Any ideas?
ID must be unique.
You can do something like following. Add parameter in onclick function. Which will be ID of row.
echo "<input type='button' onclick='addthis(".$row['s_code'].")' value='Add!'>";
^^^
Parameter added in above code. Now javascript function can be:
function addthis(scope) {
alert(scode);
}
As I stated in comments, the ID of your input must be unique. You're currently assigning 'sim' as the ID to every input in your loop over the data results.
One approach to fix this:
$i = 0;
echo "<input type='text' id='sim" . $i ."' value='".$row['s_code']."' readonly>";
And then add a unqiue id to your button using the same incrementor:
echo "<input type='button' id='btn" . $i . "' value='Add!'>";
$i++; //then increment
Notice that the button and the input have the same number at the end of their id. You can use this to parse the id of the button and use it to find the input.
Tie the click event with:
$(document).on('click', '[id^="btn"]', function() {
var id = $(this).attr('id').split('btn')[1];
var val = $('#sim' + id).val();
console.log(val);
//do other stuff
});
UPDATE: JSFiddle
I am using php and have less experience in it. I am displaying data in a table, which has a radio button at the start of each row. I want to retrieve all the data that is present in the row corresponding to the radio button I check.
Here is something what I have done till now:
<form name="test" method="POST">
<table>
<tr>
<th></th>
<th>book_id</th>
<th>card no</th>
<th>fname</th>
<th>lname</th>
</tr>
<?php
$conn = mysql_connect("localhost", "root", "");
if ($conn) {
mysql_select_db("library");
} else {
echo 'no such database';
}
$query_test = "select book_id2,a.card_no,fname,lname from book_loans a, borrower b where a.card_no = b.card_no ";
$result = mysql_query($query_test);
if ($result === FALSE) {
mysql_error();
} else {
while ($rows = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td><input type='radio' name='test'></td>";
echo "<td>" .$rows['book_id2']. "</td>";
echo "<td>" .$rows['card_no']. "</td>";
echo "<td>" .$rows['fname']. "</td>";
echo "<td>" .$rows['lname']. "</td>";
echo "</tr>";
}
}
?>
<input type="submit" name="test_val" value="submit"/>
</table>
</form>
Here I want to print the data i.e. book_id, card_no, fname, lname as the submit button is clicked:
<?php
if($_POST)
{
if(isset($_POST['test_val']))
{
// TO PRINT THE DATA CORRESPONDING TO THE RADIO BUTTON
}
}
?>
Add hidden input fields in each of the <td> rows. For example:
echo "<td>".$rows['book_id2']."</td><input type='hidden' name ='book_id2' value='".$rows['book_id2']."' />";
I've tried writing the JavaScript but this is much easier in JQuery. Add these scripts before the end of the closing </body> tag.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var toggleInput = function(){
$('input[type=hidden]').prop('disabled', true);
var selection = $('input:checked').eq(0);
selection.parent().parent().find('input[type=hidden]').each(function(){
$(this).prop('disabled',false);
});
}
$(form).on('submit',toggleInput);
</script>
JQuery is used a lot in manipulating the DOM like this. It cuts out a lot of the repetition that can be seen in JavaScript. Although if it is easier to do something with just JavaScript, then do it!
On form submission, we're disabling all hidden elements. Then we find the active radio box, and activate the hidden elements corresponding to the radio box.
This is one solution and might need to be tweaked. JavaScript and JQuery are your friends for this problem.
You could add the data as the value attribute of your radio button
echo "<input type='radio' name='test' value='".$rows['book_id2']." ".$rows['card_no']." ".$rows['fname']." ".$rows['lname']."'>";
Then the name of the post variable will be the name of the radio button
if(isset($_POST['test']))
{
echo $_POST['test'];
}
Another example, to access individual values:
echo "<input type='radio' name='test' value='".addslashes( json_encode($rows) )."'>";
if(isset($_POST['test']))
{
$result = json_decode( stripslashes($_POST['test']) ) ;
echo $result->book_id2;
echo $result->card_no;
echo $result->fname;
echo $result->lname;
}
Try implementing this:
Create a hidden textarea (which will be holding data corresponding to the radio button)
Assign a dynamic id (unique) to the <tr> and <td> and once the respective radio button is clicked, create JS function which will capture all the data w.r.t the row and if a new radio is clicked, it will clear out the old data and replaces it with new.
Submit the data and you can capture that required data.
Functions you wil require (Inbuilt and User Defined):
1 $( "#tr_unique td_unique" )[.text()][1]; // text() Since you are storing data in td else it would be val()
2 insertData(number){
// Here number is the row # through which you'll track corresponding data
}
3 $( "#hidden_textarea" )[.val][1]('data')
See, if that helps.
I want to make my table editable only for columns with Home_Score and Away_Score names
//edit.js file
$(function() {
//when a td element within tbody is clicked
$('tbody').on('click','td',function() {
//call displayform, passing td jQuery element
displayForm( $(this) );
});
});
//table.php file
<?php
$sql = "SELECT * FROM predict WHERE Fixture_ID BETWEEN '1' and '10' ";
$results = $dbh->query($sql);
$rows = $results->fetchAll();
foreach ($rows as $row) {
echo '<tr id="'.$row['Fixture_ID'].'">';
echo '<td class="Home_Team">'.$row['Home_Team'].'</td><td class="Home_Score">'.$row['Home_Score'].'</td>';
echo '<td class="Away_Score">'.$row['Away_Score'].'</td><td class="Away_Team">'.$row['Away_Team'].'</td>';
echo '</tr>';
}
?>
assuming you be adding rows you can add a class to just the rows you put the vales
<?php
$sql = "SELECT * FROM predict WHERE Fixture_ID BETWEEN '1' and '10' ";
$results = $dbh->query($sql);
$rows = $results->fetchAll();
foreach ($rows as $row) {
echo '<tr id="'.$row['Fixture_ID'].'">';
echo '<td class="Home_Team">'.$row['Home_Team'].'</td><td class="Home_Score editable">'.$row['Home_Score'].'</td>';
echo '<td class="Away_Score editable">'.$row['Away_Score'].'</td><td class="Away_Team">'.$row['Away_Team'].'</td>';
echo '</tr>';
}
?>
then you can update your selector
$('tbody').on('click','.editable',function() {
I believe you could do this
$(function() {
//when a td element within tbody is clicked
$('tbody').on('click', 'td.Home_Score, td.Away_Score', function() {
//call displayform, passing td jQuery element
displayForm( $(this) );
});
});
Alternatively, as suggested in another answer, add another class to the cells you want to be able to edit, and use that as the selector.