I have an html table built from a database query which loops through and creates a button for each camera name found and puts them in a table:
<?php
for($i=0;$i<$num_rows;$i++)
{
?>
<tr>
<td>
<input type="submit" class="play" data-hash="<?php echo $result_cameras[$i]["camera_hash"]; ?>" value="<?php echo $result_cameras[$i]["camera_name"]; ?>">
</td>
</tr>
<?php
}
?>
This resolves to something like this:
<tr>
<td>
<input type="submit" class="play" data-hash="0d3d0ac6e54a640c73f1149d4d0bbc38e99d10f5" value="Office Window">
</td>
</tr>
<tr>
<td>
<input type="submit" class="play" data-hash="b824cba374c3d5ab7806ad8260c939323c03147b" value="aaa">
</td>
</tr>
<tr>
<td>
<input type="submit" class="play" data-hash="ec9658f0c1855e2e2ac09ae284f5e6990dbf445d" value="laptop">
</td>
</tr>
Notice the data hash attribute is different for each button. I want to process this button with my jquery code:
$(".play").click(function(){
var camerahash = $('input').data('hash');
console.log($('input').data('hash'));
});
No matter which button I click I will always get the hash from the first button I click: 0d3d0ac6e54a640c73f1149d4d0bbc38e99d10f5. Any help is appreciated.
$('input').data('hash') gives you the data attribute of the first input in the selection use $(this).data('hash') to get the data attribute of the currently clicked input
You need to specify which input element to read.
Try something like:
$(".play").click(function(){
$this = $(this);
var camerahash = $this.data('hash');
console.log($this.data('hash'));
});
You are always calling the first object of .play. This would be a correct way:
$('.play').on('click', function(){
var camerahash = $(this).data('hash');
});
You could always grab them by using the .attr(data-hash) html5 attribute.
Try:
$('.play').on('click', function() {
var _hash = $(this).attr('data-hash');
console.log(_hash);
});
Your selector will return the first one that it comes to. Use this instead
<script>
$("input.play").click(function() {
alert($(this).data('hash'));
});
</script>
Related
I have the following table dynamically generated using php and MySQL. The number of rows and number of buttons generated are dynamic.
<?php
if($resultCheck != 0){
while($result = mysqli_fetch_array($tableQueryExecute)){
$normalShiftDuration = $result['shift1Duration'];
?>
<tr> <form method="post" id="vtagViewTwo">
<td name=""><select class="form-control" name="normalShiftOa" id="normalShiftOa"><option>1</option></select></td>
<td>
<input type="submit" class="btn btn-primary" name="editButton" id="editButton" value="Save">
</td>
</form></tr>
<?php
}
}
?>
I want to get value of the <td> which is normalShiftOa value with the button click using jQuery click event as below.
$("#editButton").click(function(){
alert("Clicked");
});
But since there are many button generating for each row with the same id, I am not able to do it. Does anyone know how to do it? I am able to do it using php $_POST['editButton'] method. But I want to do it using jQuery.
Edit 1
I changed the id editButton to class and tried the following. But it is not working
$(".editButton").click(function(){
alert($(this).$("#normalShiftOa").val());
});
Instead of using ids, use class editButton. Then, if you want to get the value of the select, use jQuery like shown below:
$(".editButton").click(function(){
let tdValue = $(this).closest("form").find("select").val();
});
Edit: Code snippet that works.
$(".editButton").click(function(event){
let tdValue = $(this).closest("form").find("select").val();
alert(tdValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<tr> <form method="post" id="vtagViewTwo">
<td name=""><select class="form-control" name="normalShiftOa" id="normalShiftOa"><option>1</option></select></td>
<td>
<input type="submit" class="editButton btn btn-primary" name="editButton" id="editButton" value="Save">
</td>
</form></tr>
I have a table that is being populated by a foreach loop to get data from a database:
foreach ($retrieve_data as $retrieved_data) {
$content .= "
<tr id=\"id_$retrieved_data->id\">
<td> $retrieved_data->id </td>
<td> $retrieved_data->posname </td>
<td> $retrieved_data->month </td>
<td> $retrieved_data->year </td>
<td> $retrieved_data->availableinv </td>
<td> $retrieved_data->maxinv </td>
<td> <button type=\"button\" id=\"editImpressionsBtn\" value=\"Edit\">Edit </button>
</tr>";
}
I want to write a jQuery function that gets data from the table like the id, availableinv, and maxinv when the edit button is clicked.
jQuery(document).on('click', 'editImpressionsBtn', function() {}
How can I assign a variable in this function to the data in each of these columns for only the row that the edit button was clicked?
Something like this? One thing I noticed, you need to make sure to add the selector (. or # for class or ID) to the handler.
$('.table_selector tbody').on('click', '.editImpressionsBtn', function(){
row = $(this).closest('tr');
})
Then you can add values or ids and get them like this
var my_id_value = row.attr('id')
Target the TR and then the different TD's
$('#editImpressionsBtn').on('click', function() {
var tr = $(this).closest('tr');
var tds = tr.find('td');
var id = tds.eq(0).text();
var avb = tds.eq(4).text();
});
If you're generating more than one table on the serverside, make sure you don't use the same ID for all of them, use a class instead.
There are three parts to this answer. Two are core to your question, one is a coding option / improvement:
First:
As your table is being built in a loop, I presume you've got multiple rows. Be aware that you can not have multiple buttons with the same ID. This is not only semantically incorrect, it will cause issues with jQuery. So, change the id of the button to be a class instead:
<button type="button" class="editImpressionsBtn" value="Edit">Edit </button>
Second:
Now, in your jQuery, you can access that row fairly easily:
jQuery(document).on('click', 'button.editImpressionsBtn', function() {
var row = $(this).closest('tr');
var id = row.find('td:eq(0)').text();
var posname = row.find('td:eq(1)').text();
// ... etc
});
Third:
Escaping quotes inside of quotes like you are doing is a pain to code, and more difficult to maintain and read. I'd recommend in this case using a HEREDOC.
Example:
$content .= <<<HTML
<tr id="id_$retrieved_data->id">
<td> $retrieved_data->id </td>
<td> $retrieved_data->posname </td>
<td> $retrieved_data->month </td>
<td> $retrieved_data->year </td>
<td> $retrieved_data->availableinv </td>
<td> $retrieved_data->maxinv </td>
<td> <button type="button" class="editImpressionsBtn" value="Edit">Edit </button>
</tr>
HTML;
I have html table generated via ajax. And last column on this table contains button. My question is what is the best practice to submit these rows (only one at time. I need use this method to amend records).
Is it worth to wrap each row with
<form>
<input type="hidden" value="hidden value">
<input type="submit">
</form>
Or people using something difference? Reason why i'm asking for is because i'm worry about very long list example 1k rows or 10k rows (that means i will have 1k or 10k forms on a page).
You can just use a hyperlink (which you can style to look like a button using CSS if you want). e.g:
Edit
where the value you give as the "id" parameter is the primary key of the record in that row.
Then in edit.php look for the id value using $_GET["id"] and fetch the appropriate record from the DB.
As Progrock advises, a form element may only be used "where flow content is expected" (i.e. not as a direct child of table or tr).
HTML 5 introduces a form attribute as a workaround:
<form id="row_1">
<input type="hidden" name="id" value="pk1">
</form>
<form id="row_2">
<input type="hidden" name="id" value="pk2">
</form>
<table>
<tr>
<td> <input type="text" name="attribute1" form="row_1"> </td>
<td> <input type="submit" form="row_1"> </td>
</tr>
<!-- and so on for each row -->
</table>
It has been brought to my attention that in this case, there is no direct user input being submitted, but only generated contents.
Well, then the solution is even simpler:
<table>
<tr> <td>
<form id="row_1">
<input type="hidden" name="id" value="pk1">
<input type="hidden" name="attribute1" value="whatever">
<input type="submit">
</form>
</td> </tr>
<!-- and so on for each row -->
</table>
I thought I'd have a go without form elements, working with editable table cells. Within each row you provide a button. And when you click it, an ajax post is made of the cell values.
You could have a non js fall back where the save button is replaced for an edit button that takes you to another page with a single form.
Forgive my JS.
I have the session storage in there just to check the concept.
<?php
session_start();
var_dump($_SESSION);
$data = array(
23 => ['triangle', 'green', '2'],
47 => ['square', 'red', '3'],
17 => ['pentagon', 'pink', '4']
);
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// Save state here
$_SESSION['submission'] = $_POST;
}
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(function() {
$('button').click(function() {
// Get all table cells in the buttons row
var $cells = $(this).closest('tr').find('td[contenteditable="true"]');
var jsonData = {};
$.each($cells, function() {
jsonData[get_table_cell_column_class($(this))] = $(this).text().trim();
});
jsonData['id'] = $(this).attr('id');
$.post('',jsonData, function() {
alert('Saved.');
});
});
function get_table_cell_column_class($td)
{
var $th = $td.closest('table').find('th').eq($td.index());
return $th.attr('class');
}
});
</script>
</head>
<body>
<table>
<thead>
<tr>
<th class="shape">Shape</th>
<th class="colour">Colour</th>
<th class="width">Width</th>
<th>Ops</th>
</tr>
</thead>
<tbody>
<?php foreach($data as $key => $row) { ?>
<tr>
<?php foreach($row as $field) { ?>
<td contenteditable=true>
<?php echo $field ?>
</td>
<?php } ?>
<td>
<button id="<?php echo $key ?>">Save</button>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</body>
</html>
You can use the following
<table id="YourTableId">
...
<tr data-id="yourrowId">
<td class="col1"> value1</td>
<td class="col2"> value2</td>
<td class="col3"> value3</td>
<td class="actions">
Submit
</td>
</tr>
....
</table>
your javascript code will be like
$(document).ready(function (){
$('#YourTableId a').off('click').on('click',function(e){
e.preventDefault();
var tr = $(this).closest('tr')
var data={ // here you can add as much as you want from variables
'id' : tr.data('id), // if you want to send id value
'col1': tr.find('.col1').text(),
'col2': tr.find('.col2').text(),
'col3': tr.find('.col3').text(),
};
$.ajax({
method: 'post',
url: 'your url goes here',
data: data,
success: function(result){
// handle the result here
}
});
});
});
Hope this will help you
I want to get the values of a dynamic created table but I couldn't figure out what is wrong.
the table created in a php file or it creates in server side by calling it in jquery.
for making it clear : in my html page I run a jquery method to load this table.
then I need this table values to be able to edit them. but what I get instead of the element value is undefined. (when I alert the value)
this is the jquery code :
//<!-- ajax Post Request -->
$(function() {
$('#edit_test_show').hide();
$('#save_edit').hide();
var vop_id = localStorage.getItem('op_id');
$.post("Requests/OPS.php", //Required URL of the page on server
{ // Data Sending With Request To Server
read_OPS: true,
op_id: vop_id
},
function(response) { // Required Callback Function
if (response) {
$("#result_table").html(response);
}
});
//====================
$('#enable_edit').on('click', function() {
$('#edit_test_show').show();
$('#enable_edit').hide();
$('#save_edit').show();
});
$('#save_edit').on('click', function() {
$('#edit_test_show').hide();
$('#enable_edit').show();
$('#save_edit').hide();
var vop_id = localStorage.getItem('op_id');
var vop_title = $('#result_table').find('#op_title').val();
var vop_descrip = $('#result_table').find('#op_descrip').val();
alert(vop_title);
});
});
html part which the table loads in :
<form method='post' class="form-inline">
<div class="form-group">
<div id="result_table">
<!-- dynamic op load -->
</div>
</div>
</form>
<button type='button' id="enable_edit" class='btn btn-default'>edit</button>
<button type='button' id="save_edit" class='btn btn-default'>save</button>
and this is the php code which generate the table :
if($row=mysqli_fetch_assoc($read_op)) {
echo "
<table class='styled-table' cellspacing='0' width='360' border='1' >
<tr>
<td>
<label for='mail_num' style='margin-right:10px;color:#595959;float: right;'>شماره فرآیند : </label>
</td>
<td>
<input name='op_id' style='width:240px;height: 25px;margin:0 3px 0 3px;'
value='".$row['id']."'/>
</td>
</tr>
<tr>
<td>
<label for='op_title' style='margin-right:10px;color:#595959;float: right;'>عنوان فرآیند : </label>
</td>
<td>
<input name='op_title' style='width:240px;height: 25px;margin:0 3px 0 3px;'
value='".$row['op_title']."'/>
</td>
</tr>
<tr>
<td>
<label for='op_descrip' style='margin-right:10px;color:#595959;float: right;'>شرح فرآیند : </label>
</td>
<td>
<textarea name='op_descrip' class='textarea_2' rows='0' cols='0' >".$row['op_descrip']."</textarea>
</td>
</tr>
</table>
<div class='cleaner h20'></div>";
}
You are using ID Selector (“#id”) but not defined ID in HTMl thus you are not able to find element
Define the IDs as
<input id='op_id' value='".$row['id']."'/>
OR, Use Attribute Equals Selector [name=”value”]
Selects elements that have the specified attribute with a value exactly equal to a certain value.
var vop_title = $('#result_table').find('[name=op_title]').val();
var vop_descrip = $('#result_table').find('[name=op_descrip]').val();
I have a table where it's rows are generated by a foreach loop.
Each table row has two columns, one with a form and the other with the forms submitted data, which I have called notes. (and updates using a jQuery library without refreshing the browser).
<script>
$(".notes_column").each(function(){
var $myform = $(this).find('.notes_form');
var $mynotes = $(this).find('.notes');
$myform.validate({
submitHandler: function(form) {
$.post('process.php', $myform.serialize(), function(data) {
$mynotes.html(data);
});
}
});
}); // each function
</script>
<table id="myTable" class="tablesorter" border="1" cellpadding="5">
<thead>
<tr>
<th>Notes</th>
<th>Submit Note</th>
</tr>
</thead>
<tbody>
<?php
foreach($myarray as $myvar){
echo '
<tr>
<td>ID LIKE TO PLACE THE content of the div class="notes" HERE, HOW CAN I DO IT?</td>
<td class="notes_column">
<form class="notes_form" action="" method="post">
<input class="q" type="text" name="notes" size="30" placeholder="Place your notes here..." />
<input class="searchsubmit" type="submit" name="submit" value="Submit" />
</form>
<div class="notes"></div>
</td>
</tr>
';
}
?>
</tbody>
</table>
Right now I use a jQuery each function which iterates through each table column, and for each column with the class name ".notes_column" populates a div with the class "notes" with the submitted data.
The question is listed inside the code with capitalized letters, how can I populate the other column with the forms submitted data?
Any ideas?
Ty
I would create a <div> in the first <td> such as
<td>
<div class="put_notes_here">ID LIKE TO PLACE THE content of the div class="notes" HERE, HOW CAN I DO IT?</div>
</td>
Then populate it the same as you did before
$mynotes.closest("tr").find(".put_notes_here").html(data);
Change the selector for your each to $('#myTable tr'), then you can iterate through each in your table.
Then you could either do an each on the tr object to access each td, or make use of jQuery's :first-child and nth-child(2) etc in a subsequent selector