Clear hidden value when navigating table rows using hover timeout - php

Hello guys just need a little help here. I hope you can help me.
Here's the scenario:
In my category table there's a lot of rows. Every row has a hidden textbox with an empty value and a unique id. When the user navigates, the comments for that category will display below together with the comment form for that.
If the user hovers in a specific category/rows for three(3) seconds the hidden value will get the id of the category and assign it to my hidden textbox. If the user didn't stay hovered for at least 3 seconds in a row, nothing will happen.
After that if the user hovered over another row for 3 seconds the previous hidden text value should be clear and assign a new value for the hovered row.
My problem is, when I navigate the rows and stay hovered for three seconds I can get the correct hidden value. But when I go to another row I can also get the correct hidden values but the previous hidden didn't clear or reset. How can I do that?
Here's my code, I hope you understand my point guys. Thanks.
<?php
foreach($queryViewEntries as $row){
$temp_id = $row['salescatid'];
$cat_id = $row['salescatid'];
echo '<tr>'
.'<td width="5%" style="text-align: center">'
.'<input type="text" name="indicator" value="" class="indicator" id="indicator'.$temp_id.'" style="width: 16px" />'
.' '
.'<input type="checkbox" name="category[]" value="'.$row['salescatid'].'" id="check'.$row['salescatid'].'" onclick="check(this)" id="comment'.$row['salescatid'].'" />'
.'</td>'
.'<td width="10%">{'.$row['salescatname'].'}</td>'
.'<td class="hover_comment">'
.'<span style="display: none;">{'.$row['salescatid'].'}</span>'
.'{'.$row['salescatdesc'].'}'
.'</td>'
.'<td width="30%" style="text-align: center;" class="hover_comment">'
.'EDIT'
.'DELETE'
.'</td>'
.'</tr>';
}
//HERE I SET THE HIDDEN TO A SIMPLE TEXTBOX(named 'indicator') SO THAT I CAN SEE THE VALUE INSIDE
?>
//BELOW IS MY JQUERY CODE
$(function(){
var counter = 0,
myInterval = null,
temp = null,
salesid = null;
$(".hover_comment").hover(function(e){
counter = 0;
myInterval = setInterval(function(){
++counter;
console.log(counter);
}, 1000);
salesid = $(this).find('span').text();
$(".comment_boxes").hide();
setTimeout(function(){$(".comment_box_"+salesid).fadeIn()});
$('#txt_id').val(salesid);
$(this).find(".tempid").val();
$("#comment_add").show();
},function(e){
clearInterval(myInterval);
if(counter > 3){
$("#indicator").val('');
alert(counter);
//alert(salesid);
$("#indicator"+salesid).val(salesid);
}
});
});

Use a JQuery wildcard ^ selector to clear all the #indicator elements:
$("[id^=indicator]").val('');
The caret ^ means to select all rows that have an ID starting with "indicator".

Related

PHP and jQuery - pushing input values into an array to be POSTed

I'm building a form - a section of which dynamically generates and increments input field's individual ids when the user hits the 'replicate' button. For instance, an input field made for a first name has an id of 'firstname1', when it replicates it becomes 'firstname2' etc etc.
My problem is in the php 'confirmation' page I'm trying to build. I want to echo out every input field generated and filled without hardcoding a bunch of echoes. I was told to use arrays instead of individual variable names - i kind of understand the concept but am falling way short.
I tried to create an array to capture the value of every new input so I can just $_POST the array, then loop and echo each value, but I don't really understand what needs to change and where to implement it.
The following code replicates the entire container div, it's input fields, and increments it's class number:
$(#replicate').click(function(){
var $cloned = $('.container1').clone();
$cloned.find('input').val('');
$cloned.appendTo($('.emptyContainer'));
var container = $(".emptyContainer div").length;
var containerNumber = container + 1;
var containerClass = 'container' + containerNumber;
$(".emptyContainer .container1").attr("class", containerClass);
Then the input ids increment in the same fashion:
var fnameID = 'firstname' + containerNumber;
$('.emptyContainer #firstname1').attr({id: fnameID, name: fnameID});
There are more inputs that would include things like last name, phone, email etc.
Another user suggested:
foreach($_POST as $fieldName=>$fieldValue){
echo $fieldName." = ".$fieldValue."<br/>";
}
While that worked to get me everything on the php page it was all in one large block, which would make the later styling a bit troubling.
How do I grab the input values for each new input, store them in an array, and post them to the php side in such a way that all related information stays in it's related areas when the user hits submit?
You can try following method, as this method works best for me in case of dynamic rows.
code is not much readable since i directly pasted from the project but still hope it would be helpful
$('.add-option').live('click',function(){
if(rowCtr < ucount){
var tr = '<tr class="input-'+counter+'"><td><select id="itb_users" class="itb_users" name="project[itb_users]['+counter+']" >'
tr += '<option value=0>Select</option>'
<?php foreach ($itb_users as $item){ ?>
tr += '<option grade="<?php echo $item->grade; ?>" value="<?php echo $item->id; ?>"><?php echo $item->first_name; ?></option>';
<?php } ?>
tr += '</select>'
tr += '</td>'
tr += '<td> </td>'
tr += '<td><input class="_hour" id="project[input-hour]['+counter+']" name="hours['+counter+']" type="text" class="field" style="width:30px"/></td>'
tr += '<td><img class="add-option" src="'+'<?php img_src('add.png'); ?>'+'" /> <img class="remove-option" src="'+'<?php img_src('remove.png'); ?>'+'" /></td>'
tr += '</tr>';
counter++;
rowCtr++;
.......
on submitting the php will receive a variable project with related records.

How to insert numbers rather than option type into a textbox

I need helping appending values into a textbox. What happens is that with the relevant piece of code below, the user can add an "Option Type" from a table row into the textbox. For example if the user clicks on the "Add" button and within that row the Option Type is "A-D", it adds "A-D" in the textbox. But I don't want it to add "A-D" into the textbox. I want it to add a number with the textbox instead except for "True or False" and "Yes or No" options, they can be inserted as they are. The numbers for each option type is as follows:
Option Type Number
A-C 3
A-D 4
A-E 5
A-F 6
...
A-Z 26
True or False True or False
Yes or No Yes or No
My question is how can insert the numbers for all letter option types (True or False and Yes or No remain the same) into the textbox?
Below is the relevant code where it inserts the option type from the table row into the textbox:
Table row and add button:
echo "<table border='1' id='resulttbl'>
<tr>
<th class='optiontypeth'>Option Type</th>
</tr>";
foreach ($searchResults as $key=>$question) {
echo '<td class="optiontypetd">'.htmlspecialchars($searchOption[$key]).'</td>';
echo "<td class='addtd'><button type='button' class='add' onclick=\"parent.addwindow('$searchOption[$key]');\">Add</button></td></tr>";
}
echo "</table>";
Below is the textbox the option types are currently inserted into:
<input type="text" name="gridValues" class="gridTxt maxRow" id="mainGridTxt" readonly="readonly" />
Below is the function where it currently inserts the option type into the textbox above:
function addwindow(gridValues) {
if(window.console) console.log();
if($(plusbutton_clicked).attr('id')=='mainPlusbutton') {
$('#mainGridTxt').val(gridValues);
}
$.modal.close();
return false;
}
Add a check before you change the value of the input field, something like:
if( questionText != "True or False" && questionText != "Yes or No" )
{
// caution pseudo-code ahead:
var myNumbers = {};
myNumbers["A-C"] = "3";
myNumbers["A-D"] = "4";
// ...
myNumbers["A-Z"] = "26";
questionText = myNumbers[questionText];
}
$('#mainGridTxt').val(questionText);
There are lots of other ways to go about converting the questionText into the correct number, but I was simply showing the logic for you can accommodate non-T/F or -Y/N responses.

Getting table elements in same row with jquery

I am really confused about how I can do this. I need to get the value of two <td> when one is selected. For example, below let's say I select the td with id=monthly of $550 dollars. I need to get the age and excess that corresponds with that price. I hope this makes sense. SO in the example of selecting $550 I need jQuery to get the values age(18-24) and excess($1000). I then will take these two values and insert into mysql as noted below. Is there anyway I can do this with either jQuery or PHP? I am open to ideas.
<table>
<tr>
<td width="67"></td>
<td width="102" id="excess">$1000</td>
<td width="102" id="excess">$2000</td>
</tr>
<tr>
<td width="67" id="age">18-24</td>
<td width="102" id="monthly">$550</td>
<td width="102" id="monthly">$650</td>
</tr>
<tr>
<td width="67" id="age">25-29</td>
<td width="102" id="monthly">$750</td>
<td width="102" id="monthly">$850</td>
</tr>
</table>
MYSQL(using the example above):
$query = mysql_query("UPDATE table SET Monthly = '$550' WHERE Age = '18-24' AND Excess = '$1000'")or die(mysql_error());
Your HTML is invalid. You cannot have more than one element with the same id, id values (as the name suggests) must be unique. If you're trying to classify elements, use a class. The rest of this answer assumes those id values have been changed to class names.
If I understand you, you want to handle clicks on cells with the monthly class and get the text of the first cell in the row along with the first cell in the column. This is easily done with jQuery (live example | source):
$("td.monthly").click(function() {
var $this = $(this),
firstCellInRow = $this.closest('tr').find('td').first(),
firstCellInColumn = $this.closest('table').find('tr').first().find('td').eq($this.index());
console.log("First cell in row: " + firstCellInRow.text());
console.log("First cell in column: " + firstCellInColumn.text());
});
We find the first cell in the row by finding the row via closest, then finding its first cell via find and first.
We find the first cell in the column by finding the table via closest, then getting the first row via find and first, then getting the index of the clicked cell and finding the cell in the first row with the same index via eq.
$('.monthly').bind('click', function()
{
lstrMonth = $(this).html();
lstrAge = $(this).parent().find('td:first').html();
lnIndex = $(this).parent().index($(this));
lstrExcess = $(this).parent('table').find('tr:first td:nth-child('+ (lnIndex + 1) +')');
// do ajax call to a php script which execute the query
$.post('ajax/update.php',
{
age: lstrAge,
excess: lstrExcess,
month: lstrMonth
},
function(data) // success
{
// do whatever you want
});
});
I think this will work, the PHP will simplified look like:
<?php
$query = mysql_query("UPDATE table SET Monthly = '".$_POST['month']."' WHERE Age = '".$_POST['age']."' AND Excess = '".$_POST['excess']."'")or die(mysql_error());
?>

checkbox's stay checked after pagination in php

Hello i want any checkbox i am gonna check, to stay checked after pagination.
here is the code:
foreach($test as $string){
$queryForArray = "SELECT p_fname,p_id FROM personnel WHERE p_id = " .$string["p_id"]. " ;" ;
$resultForArray = mysql_query($queryForArray, $con);
$rowfForArray = mysql_fetch_array($resultForArray);
?>
<td id="<?php echo $rowfForArray["p_id"]?>" onclick="setStyles(this.id)" ><?php echo $rowfForArray["p_fname"]?></td>
<td><input id="<?php echo $rowfForArray["p_id"]?>" class="remember_cb" type="checkbox" name="how_hear[]" value="<?php echo $rowfForArray["p_fname"]?>"
<?php foreach($_POST['how_hear'] as $_SESSION){echo (( $rowfForArray["p_fname"] == $_SESSION) ? ('checked="checked"') : ('')); } ?>/></td>
</tr>
<tr>
I am geting the data from a search result i have in the same page , and then i have each result with a checkbox , so that i can check the "persons" i need for $_Session use.
The only think i want is the checkbox's to stay checked after pagination and before i submit the form!(if needed i can post the pagination code, but he is 100% correct)
In the checkbox tag use the ternary operation, without that foreach inside him:
<input [...] value="<?php echo $rowfForArray["p_fname"]?>" <?php $rowfForArray["valueToCompareIfTrue"] ? "checked='checked'" : ''; ?> />
because the input already is inside of 'for' loop, then each time of the loop will create a new checkbox wich will verify if need to being check or not.
I hope I have helped you.
A few ways to tackle this:
(Straight up PHP): Each page needs to be a seperate form then, and your "next" button/link needs to submit the form everytime they click next. The submit data should then get pushed to your $_SESSION var. The data can then be extracted and used to repopulate the form if they navigate backwards as well. Just takes some clever usage of setting the URL with the proper $_GET variables for the form.
(HTML5): This will rely more on JavaScript, but basically you get rid of pagination and then just break the entire data set into div chunks which you can hide/reveal with JavaScript+CSS or use a library like JQuery.
(AJAX): Add event listeners to the checkboxes so that when a button is checked an asynchronous call is made back to a PHP script and the $_SESSION variable is updated accordingly. Again, this one depends on how comfortable you are with JavaScript.
Just keep in mind that PHP = ServerSide & JavaScript = ClientSide. While you can hack some PHP together to handle "clientside" stuff, its usually ugly and convoluted...
I did it without touching the database...
The checkbox fields are a php collection "cbgroup[]".
I then made a hidden text box with all the values which equal the primary keys of the selectable items mirroring the checkboxes. This way, I can iterate through the fake checkboxes on the current page and uncheck the checkboxes by ID that exist on the current page only. If the user does a search of items and the table changes, the selectable items remain! (until they destroy the session)
I POST the pagination instead of GET.
After the user selects their items, the page is POSTED and I read in the hidden text field for all the checkbox IDs that exist on that current page. Because PhP only tells you which ones are checked from the actual checkboxes, I clear only the ones from the session array that exist on the POSTED page from this text box value. So, if the user selected items ID 2, 4, 5 previously, but the current page has IDs 7,19, and 22, only 7, 19, and 22 are cleared from the SESSION array.
I then repopulate the array with any previously checked items 7, 19, or 22 (if checked) and append it to the SESSION array along with 2, 4, and 5 (if checked)
After they page through all the items and made their final selection, I then post their final selections to the database. This way, they can venture off to other pages, perhaps even adding an item to the dB, return to the item selection page and all their selections are still intact! Without writing to the database in some temp table every page iteration!
First, go through all the checkboxes and clear the array of these values
This will only clear the checkboxes from the current page, not any previously checked items from any other page.
if (array_key_exists('currentids', $_POST)) {
$currentids = $_POST['currentids'];
if (isset($_SESSION['materials']) ) {
if ($_SESSION['materials'] != "") {
$text = $_SESSION['materials'];
$delimiter=',';
$itemList = explode($delimiter, $text);
$removeItems = explode($delimiter, $currentids);
foreach ($removeItems as $key => $del_val) {
//echo "<br>del_val: ".$del_val." - key: ".$key."<br>";
// Rip through all possibilities of Item IDs from the current page
if(($key = array_search($del_val, $itemList)) !== false) {
unset($itemList[$key]);
//echo "<br>removed ".$del_val;
}
// If you know you only have one line to remove, you can decomment the next line, to stop looping
//break;
}
// Leaves the previous paged screen's selections intact
$newSessionItems = implode(",", $itemList);
$_SESSION['materials'] = $newSessionItems;
}
}
}
Now that we have the previous screens' checked values and have cleared the current checkboxes from the SESSION array, let's now write in what the user selected, because they could have UNselected something, or all.
Check which checkboxes were checked
if (array_key_exists('cbgroup', $_POST)) {
if(sizeof($_POST['cbgroup'])) {
$materials = $_POST['cbgroup'];
$N = count($materials);
for($i=0; $i < $N; $i++)
{
$sessionval = ",".$materials[$i];
$_SESSION['materials'] = $_SESSION['materials'].$sessionval;
}
} //end size of
} // key exists
Now we have all the items that could possibly be checked, but there may be duplicates because the user may have paged back and forth
This reads the entire collection of IDs and removes duplicates, if there are any.
if (isset($_SESSION['materials']) ) {
if ($_SESSION['materials'] != "") {
$text = $_SESSION['materials'];
$delimiter=',';
$itemList = explode($delimiter, $text);
$filtered = array();
foreach ($itemList as $key => $value){
if(in_array($value, $filtered)){
continue;
}
array_push($filtered, $value);
}
$uniqueitemschecked = count($filtered);
$_SESSION['materials'] = null;
for($i=0; $i < $uniqueitemschecked; $i++) {
$_SESSION['materials'] = $_SESSION['materials'].",".$filtered[$i];
}
}
}
$_SESSION['materials'] is a collection of all the checkboxes that the user selected (on every paged screen) and contains the primary_key values from the database table. Now all you need to do is rip through the SESSION collection and read\write to the materials table (or whatever) and select/update by primary_key
Typical form...
<form name="materials_form" method="post" action="thispage.php">
Need this somewhere: tracks the current page, and so when you post, it goes to the right page back or forth
<input id="_page" name="page" value="<?php echo $page ?> ">
if ($page < $counter - 1)
$pagination.= " next »";
else
$pagination.= "<span class=\"disabled\"> next »</span>";
$pagination.= "</div>\n";
Read from your database and populate your table
When you build the form, use something like this to apply the "checked" value of it equals one in the SESSION array
echo "<input type='checkbox' name='cbgroup[]' value='$row[0]'";
if (isset($filtered)) {
$uniqueitemschecked = count($filtered);
for($i=0; $i < $uniqueitemschecked; $i++) {
if ($row[0] == $filtered[$i]) {
echo " checked ";
}
}
}
While you're building the HTML table in the WHILE loop... use this. It will append all the select IDs to a comma separated text value after the loop
...
$allcheckboxids = "";
while ($row = $result->fetch_row()) {
$allcheckboxids = $allcheckboxids.$row[0].",";
...
}
After the loop, write out the hidden text field
echo "<input type='hidden' name='currentids' value='$allcheckboxids'>";

PHP Mysql & Jquery dynamically populating multiple records

I want to above Master and child system by using PHP,MYSQL & JQuery.
I am attaching sample image link below See screenshot
Product Quantity and UOM is field which belong to MAster Table and
Code, Component, category, quantity (Also) & UOM (duplicate) is belong to Child table.
I want to add Code, Component, category, quantity etc multiple time whenever user click on add.
Just need to know how can i save all these multiple records when someone completed their works and click on Final Save Button?
I am really and very aggressively searching for this but didn't get any anwer.
If anyone who can find the way or any help or anything that will help me towards this system.
Thanks a lots pls pls Help
you'll want to use
jQuery ajax to save data
.clone() to add a record in the UI you'll have to reset the values will your at it
that should get you started
Each time your user clicks 'add' you want to take the values of your form inputs, build a new table row and show their selected values. This is easy enough, but you also need to add hidden inputs which represent what they chose in the select boxes above, so when the user clicks save, the whole form is posted and you can process the input. A simple example would be:
<script>
var count = 0;
$('#add').click(function(event)
{
var code = $('#code').val(),
component = $('#component').val()
category = $('#category').val(),
uom = $('#uom').val();
$('#table').append(
'<tr>'
+ '<td>' + code + '<input type="hidden" name="record[' + count + '][code]"></td>'
+ '<td>' + component + '<input type="hidden" name="record[' + count + '][component]"></td>'
+ '<td>' + category + '<input type="hidden" name="record[' + count + '][category]"></td>'
+ '<td>' + uom + '<input type="hidden" name="record[' + count + '][uom]"></td>'
+ '</tr>'
);
/*
EDIT: I changed this to a DECREMENTOR so our keys don't overlap and override
anything that is CURRENTLY in the database
*/
count --;
})
</script>
This would attach a click handler to the add button. Each time it is clicked, we get the values of the inputs, store them in a variable, and build + append a new table row to your "preview table" below, which shows the values they selected and creates hidden inputs which can be processed later after the user clicks Save.
Some notes about this:
- it only gets the value of the selected inputs (so for the select boxes, the value of the option not the text. you'll have to do some extra work to replace that into your table row.
- your entire table will have to be encapsulated in a <form> tag, which your save button must also be inside.
Once you get the posted data to the server, do a print_r($_POST) to see what it looks like, you should be able to figure out how to process it fairly easily.
edit
Okay, so you asked a lot of questions here, i'll try to address them as best I can, without writing a novel.
What if someone mistakenly clicks on add and wants to cancel the addition (or changes their mind, whatever).
This actually isn't that hard. If this happens, just remove the appended table row from your table using $.remove. Since all the hidden input elements are contained within the table row, they will also be removed from the form so when the user posts, the fields will not be present.
How should you sanitize the data?
Sanitize the data when the user clicks add, as you populate the form, instead of afterwards, just before you post the form. It will be easier to deal with the input errors when the user clicks add than it will be to deal with them when they click save.
How can you use this method if you want to modify existing records in the database?
There's a few different ways you can handle this. The easiest way is to pre-populate your form with table rows for each existing row in your database, and add an id (assuming you have an auto-increment primary key for each row) input value for that record on the table row. This way when you're processing the form, you'll be able to see if it's an existing record by checking for the existence of the id in the posted data and verifying that it exists in your database. If it doesn't have an id key you know that it is a new record and you need to do an INSERT, and if it does, you can do an UPDATE or leave the record be. For DELETED rows, you'll want to loop through your POSTed data before doing any INSERTs and gather the id values that have been posted and run a query something like DELETE FROM table WHERE ID IN (<list of posted ids>). This will delete any rows that the user removed, then you can loop through the POSTed data again and insert the new rows.
An example of pre-populating this table would look something like this:
<?php
$query = "SELECT * FROM bill_items WHERE bill_id = 123";
$result = mysql_query($query);
$materials = array();
while ($row = mysql_fetch_assoc($query))
{
$materials []= $row;
}
?>
<? foreach ($materials as $material): ?>
<tr>
<td>
<?= $material['code']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][code]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['component']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][component]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['category'];
<input type="hidden" name="record[<?= $material['id']; ?>][category]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['quantity']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][quantity]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['uom']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][uom]"
value="<?= $material['uom']; ?>">
<input type="hidden" name="record[<?= material['id']; ?>][id]"
value="<?= $material['id']; ?>">
</td>
</tr>
<? endforeach; ?>
Also, a note. I changed the javascript example code above. I changed count++ to count-- because when you pre-populate the form with data that is currently in the database you are going to use the id of the material in the input key. When a user adds new data, there is a possibility that the key generated with javascript (with count++) will collide with the existing table data. To rectify this, we change it to count--. This key (in javascript) really isn't important, it's just keeping our data grouped together, so a negative value here does not affect anything.

Categories