I have a table of assignments. Within each row is a cell, that when clicked will bring up a hidden div to the right of the table. Within the div is a form that allows a user to associate a selected document with a task.
Currently the table is generated, in part, by a PHP "for" loop; I am cycling through an array and creating a new table row for each array index.
Within each row there are two table cells. I want the contents of one of the cells to be a hyperlink that, when clicked, will display a hidden div. Within the hidden div will be a form. The form will have a hidden input box, and I would like to dynamically set this value when the hyperlink is clicked.
Here is a sample of the table:
<table>
<tr>
<th>Task</th>
<th></th>
</tr>
<?php
for($i=0; $i<sizeof($task_array); $i++)
{ ?>
<tr>
<td><?php echo $task_array[$i]['task'];?></td>
<td>Attach Doc</td>
</tr>
}
?>
</table>
Here is the hidden div and form:
<div id="hidden_div">
<form action="[url]" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="hidden" id="task_id" value="">
<input type="submit" name="submit" value="Submit" />
</form>
</div>
I know that I can do the following with JQuery to display the hidden div:
$("#hiddendiv").show();
I also know that the hidden field 'task_id' can be set with JQuery by using
$("#task_id").val() = 'some value';
The problem I am having is that, since the values are coming from an array, I'm not sure how to specify a specific value. For example, the value of a task id is found in the variable $task_array[$i]['task_id']. I could try this:
$('#show_div').click(function(){
$("#hiddendiv").show();
$("#task_id").val() = ???
});
I'm sort of stuck on specifying for which iteration to use the task id value.
My apologies if that wasn't very clear. Any help would be appreciated. Thanks.
PHP
<?php
for($i=0; $i<sizeof($task_array); $i++)
{ ?>
<tr data-task-id="<?php echo $task_array[$i]['task_id'];?>">
<td><?php echo $task_array[$i]['task'];?></td>
<td>Attach Doc</td>
</tr>
}
?>
See that I added a data-attribute named data-task-id to the tr elements that stores the task_id for that row. We can use this in a click event handler later.
JS
//bind an event handler to the `tr` elements for the `click` event to show the `tr`s children elements (the `td`s)
$('tr').on('click', function () {
$(this).children().show();
//this next line is how we get the `task_id` associated with a row
$(this).attr('data-task-id');
});
//since we bound an event handler to the `tr` elements for the `click` event it's a good idea to stop the propagation of click events on links within the `tr` elements so the event doesn't bubble up the the `tr` elements
$('tr').find('a').on('click', function (event) {
event.stopPropagation();
});
Note that .on() is new in jQuery 1.7 and in this case is the same as .bind().
Also, you need to change the #show_div element's ID for each element (IDs must be unique). I recommend just changing it to a class instead of using an id:
<td>Attach Doc</td>
Then you can bind an event handler to it like this:
$('.show_div').click(function(){
$("#hiddendiv").show();
$("#task_id").val($(this).parents('tr').eq(0).attr('data-task-id'));
});
Related
I have a while loop in PHP that selects data from a database
I want to have a complete button for each row returned which, when pressed will run an SQL Query to change the value of the status column of that particular row
my while loop is:
$stmt = $pdo_conn->prepare("SELECT * from messages where status = :status and (assigned_to = :assigned_to1 OR assigned_to = :assigned_to2) ");
$stmt->execute(array(':status' => '', ':assigned_to1' => $user_result["sequence"], ':assigned_to2' => ''));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
$i=0;
if(count($records) > 0) {
echo '<tr>
<td colspan="7">You have '.count($records).' Messages</td>
</tr>';
foreach($records as $Messages) {
$i++;
echo '<tr>
<td>'.AdminNameLookup($Messages["assigned_to"]).'</td>
<td>'.$Messages["caller_company"].'</td>
<td>'.$Messages["caller_telephone"].'</td>
<td>'.$Messages["caller_email"].'</td>
<td>'.$Messages["caller_message"].'</td>
<td><input type="submit" name="CompleteMessages['.$i.']" value="" /></td>
</tr>';
}
}
but I'm not too sure on how to handle the PHP on submit?
Before sending data you need to create html form tag. And also you have pass values using input tag values.
format tag should be like this below code.
<form action="" method="">
<input type="" value="">
<input type="submit" name="CompleteMessages['.$i.']" value="" />
</form>
I would use this instead:
<td><input type="submit" name="CompleteMessages" value="'.$i.'" /></td>
You can then get the id with:
$Id = $_POST['CompleteMessages'];
Personally I'd have $i set to $Messages["message_id"] to you can find what Id you have actually submitted.
You also need to wrap everything in a form tag:
<form action="submit.php" method="POST">
...
</form>
If you only want to change the value of the row where you clicked the submit button,
then you will need a unique key for each record.
Lets assume that the messages table has a MessageID column.
One approach would be to call a javascript function.
Let's say your javascript function was called UpdateColumn(ID,ColName,Index)
Here's what would need to be added to each input button (pseudocode)
onclick="UpdateColumn($Messages['MessageID'],'Status',$i)"
Then your javascript will need to lookup value from input CompleteMessages[Index]
The Javascript could call your request php via ajax ...
update.php?MessageID=MessageID&Column=Status&Value=CompleteMessages[Index].value
And finally your php which handles the submit would take the values
using
$MessageID=$_REQUEST["MessageID"];
$Column=$_REQUEST["Column"];
$Value=$_REQUEST["Value"];
Then you will want to run a sql query which updates your database accordingly.
I have this chunk of code, which is displayed on a user's journal page. They can add an entry and they have the option to delete an entry once it's on the page.
Ill show the code with some comments and then explain the problem.
// Figures out how many recent posts to display
$posts = $config_journalposts + 1;
if($noposts!=1) {
// Gets the data from the query
while(($row = mysql_fetch_array($journalquery)) && ($posts > 1)) {
// For each of the posts that were gathered, display the following:
echo '<table border="0" width="100%">
<tr>
<td colspan="2" style="vertical-align:bottom;">
// Display the title as a link to be used as a permalink
<p class="fontheader">'.$row['title'].'</p>
</td>
</tr>
<tr>
// Show the o-so-important content
<td width="100%" style="vertical-align:top;padding-left:10px;">
'.$row['content'].'
</td>
</tr>
<tr>
// Show the date
<td style="font-size:8pt;padding-top:10px;">'.$row['date_day'].'/'.$row['date_month'].'/'.$row['date_year'].'</td>';
// Checks if the current user is the owner of the journal or an admin
if($_SESSION['user']==$pageowner || $_SESSION['user_rank']=='Admin') {
echo '<td align="right">
// FOCUS POINT
<form method="POST" id="deljournal">
<input type=\'hidden\' name=\'delete_id\' value=\''.$row['id'].'\' />
// A delete button that executes a bit of Javascript
<button type="button" class="button" name="delete" value="Delete" onClick="delete_journal()" />Delete</button>
</form>
// END FOCUS POINT
</td>';
}
echo '</tr>
</table>
<hr>
';
$posts --;
}
Here is the Javascript that gets triggered on the button press
function delete_journal() {
var answer = confirm("Are you sure you want to delete this journal entry?")
if (answer){
// Submits the form
$("#deljournal").submit()
}
}
This javascript triggers the forum in the PHP code above which reloads the page and triggers this at the very top of the page, before the tag
if(($_POST['delete_id'])) {
// Gets the post ID from the hidden forum tag
$deleteid = addslashes(strip_tags($_POST['delete_id']));
// Deletes the row that has the ID of the hidden form
mysql_query("DELETE FROM `gamezoid_accounts`.`journal_$pageowner` WHERE `id`='$deleteid'");
}
Now, for the problem. In the while loop, this form gets repeated over and over. What happens is that upon pressing the delete button, it triggers the form that has the ID "deljournal". Since all of them have the ID "deljournal" it does the one at the top of the page. Trying to embed the post ID into the form ID breaks the code because the mysql_query doesn't know that the delete function has been triggered in the first place.
Any way around this?
Reason why I'm using Javascript as a trigger is for the confirmation popup in case anyone askes.
Anyways, thanks heaps for reading this far!
<input type=\'hidden\' name=\'delete_id[]\' value=\''.$row['id'].'\' />
then only u will get all the values as array when posted.
<input type=\'hidden\' name=\'delete_id[]\' value=\''.$row['id'].'\' />
then only u will get all the values as array when posted.
and on server side u should use
$delete_values= implode (',',$_POST['delete_id']);
Found a solution.
I have changed the form to be
<form method="POST" id="deljournal_'.$row['id'].'">
<input type=\'hidden\' name=\'delete_id\' value=\''.$row['id'].'\' />
</form>
<button type="button" class="button" name="delete" value="Delete" onClick="delete_journal_'.$row['id'].'()" />Delete</button>
by adding the journal entry ID into the ID of the form and the onClick function. The javascript is just below it outside the table cell and looks like:
<script type="text/javascript">
function delete_journal_'.$row['id'].'() {
var answer = confirm("Are you sure you want to delete this journal entry?")
if (answer){
$("#deljournal_'.$row['id'].'").submit()
}
}
</script>
where the entry ID has been added to the function name and form ID tag. By putting the Javascript into a while loop and not into an external file, it can be manipulated with the loop to have the same values.
It is a bit messy and will slightly increase load times + execution times but it was the quickest way that I could find.
Hope this helps anyone else who has been having a similar problem.
I have a html table(grid) which displays a few records for me.I want it to be editable, i.e user can edit the values and save them on pressing enter.
My table is something like this.I display records dynamically using php.
<a class="grayBucketBtn noMargin none" id="unpublish" href="#.">Unpublish</a>
<a class="grayBucketBtn" id="publish" href="#.">Publish</a>
<a class="grayBucketBtn" id="delete" href="#.">Delete</a>
<a class="grayBucketBtn" id="modify" href="#.">Modify</a>
<?php while ()//loop through ?>
<tr>
<td class="tableRadioBtn"><input type="checkbox" class="checkRowBody" id="checkRowBody" name="check"/></td>
<td class="tableShape">Round</td>
<td class="tableCarst">0.30</td>
<td class="tableColor">j</td>
<td class="tableClarity">SI1</td>
<td class="tableDimension">4.35x4.33x2.62mm</td>
<td class="tableDeptd">60.3%</td>
<td class="tableTablePer">60.3%</td>
<td class="tablePolish">Excellent</td>
<td class="tableSymmetry">Excellent</td>
<td class="tableCut">Very Good</td>
</tr>
<?php } ?>
Each row(tr) has a check box associated.If I check the check box,I get a edit button.When I click on the edit button,the selected row will turn into editable.So I want a function on the edit button,
$("#modify").click(function(){
//check if only one check box is selected.
//make it editable.
//save the content on pressing enter of the edited row.
});
I went through some questions but did not get a solution as most suggest some plugins which don't meet my requirements.So,some help would be useful.
Thanks for the time
This should cover turning them from text to inputs and back to text
$('#modify').click(function(){
$.each($(".checkRowBody:checked"),function(){
$.each($(this).parent('td').parent('tr').children('td:not(.tableRadioBtn)'),function() {
$(this).html('<input type="text" value="'+$(this).text()+'">');
});
});
});
$('input[type="text"]').live('keyup',function(event) {
if(event.keyCode == '13') {
// do $.post() here
$.each($('input[type="text"]'),function(){
$(this).parent('td').html($(this).val());
});
}
});
When using checkboxes the user assumes more than one can be selected, if you want only one each time then just use radio buttons
I can't give you a complete solution but I can give you a direction:
First change the markup like this:
<tr>
<td class="tableRadioBtn"><input type="checkbox" class="checkRowBody" id="checkRowBody" name="check"/></td>
<td class="tableShape">Round<input class="hidden" value="Round" name="shape"/></td>
<td class="tableCarst">0.30 <input class="hidden" value="0.30" name="tableCarst"/></td>
...
//Do the same for all the columns
</tr>
Define the hidden class to display:none so all the inputs are hidden.
Once the user clicks a row, you remove the text of all the td elements and remove the hidden class from all the inputs:
$(".tableRadioBtn").click(function(){
//find the parent tr, then find all td's under it, empty the text and remove hidden class
$(this).closest('tr').addClass('editable').find('td').each(function(){
$(this).text('').removeClass('hidden');
});
});
//set a keypress event to detect enter
$(document).keypress(function(){
//if enter was pressed , hide input and set text
if(e.which == 13) {
var $editable = $('.editable');
$editable.find('input').addClass('hidden');
$editable.find('td').each(function(){
//set the text back
$(this).text($(this).find('input').val());
});
//post data via ajax.
}
}
Please note that i haven't tested this code so there might be some mistakes there, but this is a possible solution.
UPDATE:
In order to detect if more than one checkbox is checked use this:
if ($(':checked').length > 1){//do something}
So you want to make your selections and then invoke an action on the checked rows?
$('#delete').click(function() {
$.each($('.checkRowBody:checked').parent('td').parent('tr'),function() {
// probably want to carry out a $.post() here to delete each row using an identifier for the rows related record.
//I suggest applying an id or other attribute to the tr element and using that to pass a value with your $.post() data.
$(this).hide();
});
});
I've used jQuery before to copy billing addresses to shipping addresses, but if I am dynamically generating form rows with various values from PHP, how do I set up the form so that upon a checkmark, a recommended item quantity will be automatically copied just to the quantity of the same item?
Here is the basic version of the billing/shipping copy script.
<script src="../Scripts/jquery-1.7.2.min.js"></script>
<script>
$(document).ready(function(){
$("input#same").click(function()
{
if ($("input#same").is(':checked'))
{
// Checked, copy values
$("input#qty").val($("input#same").val());
}
else
{
// Clear on uncheck
$("input#quantity").val("");
}
});
});
</script>
And here is the PHP code dynamically gathering items with their suggested quantity.
while( $row = mysql_fetch_array($histresult) )
{
echo '<tr height = "50px">';
echo '<td>'.$product_id.'</td>';
echo '<td>'.$suggested_quantity.'<input id="same" name="same" type="checkbox" value ="'.$suggested_quantity.'"/> </td>';
echo '<td><input name="qty" type="text"size="4" maxlength="4"></td>';
///Other form elements go here, as well as an Add to Cart Button
}
For each item, a suggested wholesale quantity based on a user's favorite items is retrieved from the database. There is also a text field so that they can enter any amount they want before sending it to their cart. But if they check the checkbox, I want it to copy that value to the text field.
No only does this code not seem to do the trick, the difference between this and the billing/shipping copy is that now I'm dealing with a dynamic number of fields. How do I make each individual row achieve this task?
Using jQuery, you would essentially want to grab the suggested value from checkbox and put it in the other form element. Let's say this is your HTML:
<table>
<tr>
<td>
100 <input id="check-1" name="same" type="checkbox" value ="100"/>
<input id="qty-1" name="qty" type="text"size="4" maxlength="4">
</td>
<td>
100 <input id="check-2" name="same" type="checkbox" value ="100"/>
<input id="qty-2" name="qty" type="text"size="4" maxlength="4">
</td>
<td>
100 <input id="check-3" name="same" type="checkbox" value ="100"/>
<input id="qty-3" name="qty" type="text"size="4" maxlength="4">
</td>
</tr>
</table>
And then this would be your javascript/jQuery:
// Bind click event to ALL checkboxes
$("#same-*").live("click", function(e) {
// Only change it if box is checked
if( $(this).is(":checked") )
{
// Get suggested value
suggested_val = $(this).val();
// Place in next element (textbox)
$(this).next().val(suggested_val);
}
)};
I haven't tested this, but this is basically how it would work.
In your PHP, you would want to dynamically make those ID numbers so each row uses a unique ID. This is usually simple enough to match to your database row id.
<td>'.$suggested_quantity.'<input id="same-' . $row->id . '" name="same" type="checkbox" value ="'.$suggested_quantity.'"/> </td>
Change your code this way
<script>
$(document).ready(function(){
$("input.same").click(function()
{
if ($(this).is(':checked'))
{
// Checked, copy values
var temp = $(this).attr("title");
$("input#qty"+temp).val($("input#same"+temp).val());
}
else
{
// Clear on uncheck
$("input#qty"+temp).val("");
}
});
});
</script>
$i=0;
while( $row = mysql_fetch_array($histresult) )
{
echo '<tr height = "50px">';
echo '<td>'.$product_id.'</td>';
echo '<td>'.$suggested_quantity.'<input class="same" id="same'.$i.'" title="'.$i.'" name="same'.$i.'" type="checkbox" value ="'.$suggested_quantity.'"/> </td>';
echo '<td><input class="qty" name="qty'.$i.'" id="qty'.$i.'" type="text"size="4" maxlength="4"></td>';
///Other form elements go here, as well as an Add to Cart Button
$i++;
}
Hope this will helpful to you
Recycling IDs/names amongst several html elements is a bad idea I find.
I think it's best to make them unique.
But anyways, here's a suggestion that won't modify your html structure a lot.
Change the form tag as follows:
<form id="Order">
...
</form>
Change your PHP code as follows (added a label tag to isolate your suggested quantity better in the DOM, got rid of some unnecessary structure for your checkboxes):
while($row=mysql_fetch_array($histresult))
{
echo '<tr height = "50px">';
echo '<td>'.$product_id.'</td>';
echo '<td><label>'.$suggested_quantity.'<label><input type="checkbox" class="Same"/> </td>';
echo '<td><input name="qty" id="qty_'.$product_id.'" type="text"size="4" maxlength="4"></td>';
///Other form elements go here, as well as an Add to Cart Button
}
Finally, here is the jQuery code:
<script src="../Scripts/jquery-1.7.2.min.js"></script>
<script>
jQuery(document).ready(function(){
jQuery("form#Order").click(function(Event){ //One event handler for the form, more efficient that way and you need less html structure to keep track of things
var Target = jQuery(Event.target); //This is the html element that got clicked on
if(Target.is("input:checkbox.Same")) //Make sure it's a checkbox that suggests quantity
{
var Text = jQuery(Target.closest('tr').children().get(2)).children(); //Get the parent TR tag, get it's third child (td tag containing the text field), get it's child (the text field)
var Suggested_quantity = Target.prev().html(); //Get the previous sibling which is the label containing the quantity and get it's html content which is the quantity
if(Target.is(":checked"))
{
Text.val(Suggested_quantity);
}
else
{
Text.val("");
}
});
});
</script>
EDIT: Removed some redundant html code. Added a class to isolate the right checkboxes. Added IDs for the text field (forgot).
I'm somewhat new to jQuery, so I could use some help here.
This is my issue:
I have a PHP script outputting a dynamic table. Each row has an "edit" button, plus some other fields. Only 3 of those need to be turned into an input box. The edit button should only put that specific row into "edit mode." I got as far as assigning each row a unique class by adding a number to the end of it.
I have been able to use jQuery to change all of the rows into edit mode, but I need it to be specific to a row.
An example row would have classes like name0, price0, and desc0. The next row would go on to classes name1, price1, and desc1 (for the fields that need changed). How can I reference these values and pass them to jQuery so it processes an event on just those elements?
There are two ways of doing this:
Dynamically creating the elements when the button is pressed; or
Hiding and showing elements that already exist.
Too much DOM manipulation can be really slow (particularly on certain browsers) so I favour (2). So for example:
<table class="editable">
<tbody>
<tr>
<td>one</td>
<td>
<div class="view">two</div>
<div class="edit"><input type="text"></div>
</td>
<td>
<div class="view">three</div>
<div class="edit"><input type="text"></div>
</td>
<td>
<input type="button" class="edit" value="Edit">
<input type="button" class="send" value="Send" disabled>
<input type="button" class="cancel" value="Cancel" disabled>
</td>
</tr>
</tbody>
</table>
with:
table.editable div.edit { display: none; }
and
$(function() {
$(":button.edit").click(function() {
var row = $(this).closest("tr");
row.find("input.view").attr("disabled", true");
row.find("div.view").each(function() {
// seed input's value
$(this).next("div.edit").children("input").val($(this).text());
}).fadeOut(function() { // fade out view
row.find("div.edit").fadeIn(function() { // fade in edit
row.find("input.edit").removeAttr("disabled"); // enable edit controls
});
});
});
$(":button.cancel").click(function() {
var row = $(this).closest("tr");
row.find("input.edit").attr("disabled", true");
row.find("div.edit").fadeOut(function() {
row.find("div.view").fadeIn(function() {
row.find("input.view").removeAttr("disabled");
});
});
});
$(":button.save").click(function() {
// ...
});
});