identify jquery button click in php rows - php

I have an input button in :
while ($row = $result->fetch()) {
echo '<table class="cart-row" cellspacing="0" cellpadding="0" width="100%">';
echo '<tbody>';
echo '<tr>';
echo '<td width="75"><img border="0" width="59px" height="78px" title="" alt="" src=' . $row["ImagePath"] .'></td>';
echo '<td width="203"><span id="itemName" class="itemElements">'. $row["Name"] .'</span></td>';
echo '<td width="135"><span id="qtyNum">('. $row["Qty"] .')</span> <br />';
echo '<span id="qtyRemoveLink"><input class="linkbtn" type="submit" id="btnRemove" value="Remove"></td>';
echo '<td width="180"><span id="orderStatus" class="itemElements">In Stock Usually dispatched within 24 hours</span></td>';
echo '<td width="175" id="itemPriceRow"><span id="itemPrice">€ '. $row["Price"] .'</span></td>';
echo '</tr>';
echo '</tbody>';
echo '</table>';
echo '<br>';
}
I'm trying to use this method to trigger an event when the button is clicked however the event is only being fired for the first button generated in the first row. I'm using this method:
$(document).ready(function() {
$('#btnRemove').click(function() {
alert("test");
});
});
Any ideas how I can fix this problem? I know in C# there is on row databound method however in jQuery I dont now if it exsists. Thanks

You are selecting an element to bind the click event handler to that has a unique ID. When you select by ID you will be returned only the first matching element because to be a valid ID it must be unique.
Change the ID to a class and change your selector to .btnRemove and the alert will work for all the buttons.
echo '<span id="qtyRemoveLink"><input class="linkbtn" type="submit" id="btnRemove" value="Remove"></td>';
Should change to:
echo '<span id="qtyRemoveLink"><input class="linkbtn btnRemove" type="submit" value="Remove"></td>';
And:
$('#btnRemove').click(function() {
Should change to:
$('.btnRemove').click(function() {
Here is a demo: http://jsfiddle.net/rSyCw/
Here is an excellent answer on the site regarding the creation of valid HTML IDs: What are valid values for the id attribute in HTML?

Use a class for the button, not an ID. IDs are unique identifiers (can only be one with that name on the whole page), however classes may be applied to multiple elements. So...
<input type="submit" id="btnRemove" />
Becomes
<input type="submit" class="btnRemove" />
And, as such, your selector changes to .btnRemove.
And, now that you know that IDs need to be unique, you should go ahead and re-configure the output to use classes, or use IDs with a unique ID appended. e.g.
<?php
while ($row = $result->fetch()){
?>
<!-- Other HTML -->
<input type="submit" id="btnSubmit_<?= $row['Unique_Column_Id']; ?>" ... />
Then you can modify your selector:
$('[id^="btnSubmit_"]').click(...); // All elements with an
// ID that starts with "btnSubmit_"

One red flag here is that you are generating multiple elements with the same ID on each iteration of your loop. Element IDs need to be unique in your document. My guess is that jQuery is only binding to the first element it finds with the ID "btnRemove" because it assumes that your IDs are unique.
As others have stated, using a class name on your button would help your problem, but you should still come up with a way to put unique IDs on your itemName, qtyNum, qtyRemoveLink, orderStatus, itemPriceRow, and itemPrice elements, and anywhere else you might be using this technique.

Related

How to post multiple entries from dynamically generated textboxes in while loop

please i am currently working on a school result computation project in php. I have a page that gets all the students that enrolled for a particular subject. A while loop generates three textboxes against each student's name(CA1, CA2, and Exam). Please can anyone help me with a solution?? When the form is submitted only the last entry enters the database. Below is my code.
<?php
session_start();
include 'header_staff.php';
$subject=$_POST['subject'];
$user_id=$_SESSION['user_id'];
$get=mysql_query("SELECT * FROM staffrecord WHERE user_id='$user_id'",$conn);
$go=mysql_fetch_array($get);
$class=$go['class_id'];
$sql=mysql_query("SELECT * FROM student_enrollment WHERE class_id='$class' AND subject_id='$subject'",$conn);
echo '<form action="submitrslt.php" method="post">';
while($subj=mysql_fetch_array($sql)){
echo $subj['name'];
echo '<input type="text" name="ca1" />';
echo '<input type="text" name="ca2" />';
echo '<input type="text" name="exam" /><br><br>';
}
echo '<input type="submit" value="submit" />';
?>
The solution to your problem is to use your input arrays by simply adding [] to the input names:
while($subj=mysql_fetch_array($sql)){
echo $subj['name'];
echo '<input type="text" name="ca1[]" />';
echo '<input type="text" name="ca2[]" />';
echo '<input type="text" name="exam[]" /><br><br>';
}
Further, you can use the primary key of your table as the index in each iteration (let's suppose this would be $subj['id'], but if it is more meaningful in your case, you can also use $subj['name'] as the index):
while($subj=mysql_fetch_array($sql)){
echo $subj['name'];
echo '<input type="text" name="ca1[<?php echo $subj['id'] ?>]" />';
echo '<input type="text" name="ca2[<?php echo $subj['id'] ?>]" />';
echo '<input type="text" name="exam[<?php echo $subj['id'] ?>]" /><br><br>';
}
This way you can easily identify values from the resulting array after the post.
PS: Be sure you never trust user input without verifying or sanitizing it - make sure $_POST['subject'] is numeric. You can find plenty of useful tips on how to achieve this.
I have added comments, this will solve your problem i am assuming your subjects data is unique for the loop. And i have defined the input with the subject name which make it unique. Just for an example you can try your own method. This will output all the post variables on your action(form post) screen.
<?php
while($subj=mysql_fetch_array($sql)){
$subname = str_replace(' ','', $subj['name']); //just to replace the space
echo $subj['name'];
echo '<input type="text" name="'.$subname.'_ca1" />'; //to make the field unique for the input entries
echo '<input type="text" name="'.$subname.'_ca2" />';
echo '<input type="text" name="'.$subname.'_exam" /><br><br>';
}
echo '<input type="submit" value="submit" />';
echo '</form>';
?>
Firstly, I would suggest changing the connection to mysqli, which follows a very similar syntax to mysql except that it is not deprecated.
Secondly, the form looks fine, except that the textboxes and submit button don't have any unique identifiers, you might try putting in a unique 'id' for each of the input fields. Since your loop is combining all input fields in one form, this is likely the culprit. Furthermore, I don't see a closing tag for form, i.e. </form>.
Finally, you should look up filter_input for handling superglobals such as $_POST[].
I assume that all fields are meant to be submitted at once rather than individually?

Saving a specific row using PHP and a search option

I have the following program, it searchs for the text placed in a previous php file, and it displays the results, by adding a radiobox to check the item that will be purchased. I am not able to make the page save the item that was checked from the items found into a new table, I don't know how to do that, because the items found are placed as fetched items, therefore I don't know how to select one to save the entire row selected. Please help!.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Search option</title>
</head>
<body>
<?php
echo "<form action='slips.php' method='post'>";
if(isset($_POST['name_prod2'])){
$word=$_POST['name_prod2'];
$conn = oci_pconnect('dbname', 'password', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['Error'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, "SELECT * FROM product WHERE LOWER(name) LIKE '%" . $word . "%'");
oci_execute($stid);
echo "<table width='950' table border='1' align='center'>\n";
echo "<tr>\n";
echo "<th width='50'> <div align='center'>buy</div></th>";
echo "<th width='110'> <div align='center'>Product ID</div></th>";
echo "<th width='190'> <div align='center'>Product name</div></th>";
echo "<th width='250'> <div align='center'>Description</div></th>";
echo "<th width='100'> <div align='center'>in Store</div></th>";
echo "<th width='100'> <div align='center'>price</div></th>";
echo "<th width='190'> <div align='center'>Quantity to purchase</div></th>";
echo "</tr>\n";
while ($product = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
//echo "<td><div style='text-align:center'><label><input type='radio' name='radio1' value='valor'></label></td></div>";
echo sprintf('<td><div style="text-align:center"><label><input type="radio" name="product" value="%s"></label></td></div>', $product['product_id']);
foreach ($product as $aspect) {
echo '<td><div style="text-align:center">'.($aspect !== null ? htmlentities($aspect, ENT_QUOTES) : '')."</td></div>\n";
}
echo '<td width="50"><div align="center"><input name="quantity" type="text" size="27" maxlength="50" placeholder="Enter quantity"></div></td>';
}
echo "</table>\n";
}
echo "<div style='text-align:center'><input type='submit' value='Comprar'></div>";
echo"</form>";
?>
</body>
</html>
These are two of the Javascripts that I have tried so far to complete this, but they fail to tell me when one has been selected, I don't know if I can try adding this code to a button, and when I click it, it will tell me which row from the radio box was checked, and then save it:
<script type="text/javascript" src="js/jquery.js"> </script>
<script type="text/javascript">
var user_cat = $("input[radio1='user_cat']:checked").val();
if (!$("input[radio1='radio1']").is(':checked')) {
alert('Nothing is checked!');
}
else {
alert('One of the radio buttons is checked!');
}
$(document).ready(function() {
$('#btnStatus').click(function(){
var isChecked = $('#rdSelect').prop('checked');
alert(isChecked);
});
});
</script>
When is use this line echo "<td><div style='text-align:center'><label><input type='radio' name='radio1' value='valor'></label></td></div>"; it works and displays this results
But when I use this line echo sprintf('<td><div style="text-align:center"><label><input type="radio" name="product" value="%d"></label></td></div>', $product['product_id']);it doesn't work and displays this results
OK, picking up the information from the comments to the question and doing a little guess work I will try to point you into the right direction. It is not possible to give a read-to-use answer, since still there are things not clear, but let's have a try to get started...
I see you have an html form which includes a table. That table has a header row and dynamic generated rows holding some product information each. You want to have a radio button in front of each row to allow to select a row. And you want a text input field at the end of each row which allows to enter a quantity. Then you want to post that information to the server to be able to process it.
I will stick with the "conservative" html approach and not introduce scripting here. Reason is that for the purpose described before that is not required. So let's keep things simple. Obviously nothing speaks against making things more complicated later on :-)
Your radio buttons have to be changed, they currently make no sense. You have to give the an individual value, so that you can identify which row has been selected later on. Currently you give them all the same static value 'value'. So change the loop that iterates over the products to something like:
while ($product = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
echo sprintf('<td><div style="text-align:center"><label><input type="radio" name="product" value="%s"></label></td></div>'."\n", $product['product_id']);
foreach ($row as $aspect) {
echo '<td><div style="text-align:center">'
.($aspect !== null ? htmlentities($aspect, ENT_QUOTES) : '')
."</td></div>\n";
}
echo '<td width="50"><div align="center"><input name="quantity" type="text" size="27" maxlength="50" placeholder="Enter quantity"></div></td>'."\n";
}
Note: I took the liberty to change the chosen names to be more logical to product, aspect and quantity...
That is all... Now when you press the submit button the form should get posted to the target you specified: slips.php which is probably a script of yours... Inside that script you now can access the data like that:
$product = $_POST['product'];
$quantity = $_POST['quantity'];
There are more issue worth discussing and modifying, but as said: let's keep things simple and take one step after the other!
ChangeLog:
changed the literal key of the array element used as a value inside the radio button definition from id to procduct_id according to one of the comments below
Your radiobox need to stay inside the form.

How to check which button have been submitted

I have a form, like this:
echo '<table align=center border=1>';
echo '<form method="post">';
echo '<tr>';
echo '<th>Lista Echipamente</th>';
echo '<th>Actiune</th>';
echo '</tr>';
while($row=mysql_fetch_array($sql)){
echo '<tr>';
echo '<td><input class="search-logi" id="tip" type="text" name="tip" value="'.$row['tip'].'"></td>';
echo '<td><input type=submit name=modifica value=Modifica></td>';
echo '</tr>';
}
echo '</form>';
echo '</table>';
Because of the loop, this form will have multiple rows. For each input, will be a button.
Lets say I want to add a value in the second input, then I will submit it (also the second button, obviously). Here comes the problem, in my code I have just a button, but the user see as many as the loop goes. How can I check which button is submitted?
Alternatively, you could utilize <button> tags for this purpose:
echo '<form method="post">'; // form tags are outside to be valid!!!
echo '<table align=center border=1>';
echo '<tr>';
echo '<th>Lista Echipamente</th>';
echo '<th>Actiune</th>';
echo '</tr>';
while($row = mysql_fetch_assoc($sql)){
echo '<tr>';
echo '<td><input class="search-logi" type="text" name="tip['.$row['id'].']" value="'.$row['tip'].'"></td>';
echo '<td><button type="submit" name="modifica" value="'.$row['id'].'">Modifica</button</td>';
echo '</tr>';
}
echo '</table>';
echo '</form>';
Then on the processing form:
$modifica = $_POST['modifica']; // shoud return the index num
$tip = $_POST['tip'][$modifica]; // select which textbox
Keep some unique reference to both input and button. Let say start a counter as 1 and then make the input id as input_1 and button as button_1 and then when you click button get the counter value that is 1 for above and then get the value of input_1 as per counter 1 and submit the form. And then increase counter so that id will increase as well. I think this will help you what you need.
Check all your $_POST variales which are empty and which are not.
Else you could write a javascript function to set all unused fields the value to "0" or to a string and check if it is used or not e.g "unused". In your php script you can check now for the value if it is set to "0" or "unused".
One way is to prefix the name of the input text field with a counter or other prefix. Bases on the name of the input field you can determine which button fired.

using jQuery to copy column specific form values

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).

Assign every TD in PHP While Loop Table a Link

I have a while loop that retrieves info from the mysql db. Now there is a column called profile. So I want every <td> in the profile to be a button that would have an action which would lead to a PHP page. How do I do that?
<form action="profile.php" method="get">
while($result)
{
echo '<table>';
echo '<tr>';
echo '<td>';
echo $result['profile'];
echo '</tr>';
echo '</td>';
echo '</table>';
}
Now every $result['profile'] should be a submit like - <input type="submit">
Thanks.
rewrite
echo $result['profile'];
to this code:
echo ''.$result['name'].'' ;
First of all,
echo '</tr>';
echo '</td>';
should be:
echo '</td>';
echo '</tr>';
To add a Submit button, change
echo '<td>';
to
echo '<td><input type="Submit" value="Submit">';
and
echo '</td>';
to
echo '</input></td>';
You will need to add the appropriate attributes to the submit button if applicable. Also, you will need to surround the submit button with a form element. Whether each link has its own form, or the entire table is surrounded by one is up to you.
Edit
To surround the table with a form tag, change echo '<table>'; to echo '<form><table>';. Then, change echo '</table>'; to echo '</table></form>';. Submit buttons are automatically "linked" to the form element they are contained in. All you have to do is to define the form action.
Edit
Actually, because you are using a GET request, this entire thing can be simplified by using links instead of forms. So go with RAMe0's answer.

Categories