using jQuery to copy column specific form values - php

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

Related

Store query element into database

table is under loop
<table>
<tr><input class="txt form-control" name="balance[]" type="text" placeholder="Balance" /></tr>
</table>
,and the balance is added from all the tr
total balance is shown on the debtsum. And it is done by jquery
<div class="col-lg-3"> <input class="debtsum form-control " id="debt" type="text" name="totaldebt" placeholder="Total Debt" disabled /> </div>
Query to store data into database :
$totaldebt = mysqli_real_escape_string($connect,$_POST['totaldebt']);//to store total debt in the database
$table_customer_data="insert into
tbl_customer_data(totaldebt) values ('".$totaldebt."');
Jquery script to add all the data of class txt :
<script>
function calculateSum() {
var sum = 0;
$(".txt").each(function () {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
$('#debt').val(sum.toFixed(2));
}
$("table").on("keyup", ".txt", function () {
calculateSum();
});
</script>
The jquery function is working properly, and sums all the input value of balance. But when i submit form to store all the value into database it stores nothing.
Thanks in advance, any help is appreciated.
I think this is issue due to disabled property in your element.
disabled element isn't editable and isn't sent on submit.
I think you can take readonly.
a readonly element is just not editable, but gets sent when the
according form submits.
for more information please click here

Auto-Populate text field from drop-down selection in dynamically added rows

I have a form in which users can dynamically add rows. In each row there is a drop-down menu of products that should auto-populate a text field with the price associated with the product chosen. This works perfectly for the first row, but does not work in the dynamically added rows. The product names are still being pulled from the mysql database into the drop-down, but it is not auto-populating the text field when chosen. Any help would be appreciated!
EDIT: I added the following section, which I think will make this whole thing work, I just need to figure out how to attach the i variable to the name or id or class, and then I can have the auto-populate code include price[i] and product[i]... and I THINK that will make it work for each dynamically added row. Any ideas now?
for(var i=0;i<$('.orderform tr').length;i++)
{
}
END EDIT
Auto-populate code:
<script>
$(function() {
$('select[name="product[]"]').change(function()
{
$('#price').val($('select[name="product[]"] option:selected').data('price'));
});
});
</script>
Adding a row code:
<script>
$(document).ready(function(){
//This line clones the row inside the '.row' class and transforms it to plain html.
var clonedRow = $('.row').clone().html();
//This line wraps the clonedRow and wraps it <tr> tags since cloning ignores those tags
var appendRow = '<tr class = "row">' + clonedRow + '</tr>';
$('#btnAddMore').click(function(){
//this line get's the last row and appends the appendRow when it finds the correct row.
$('.orderForm tr:last').after(appendRow);
for(var i=0;i<$('.orderform tr').length;i++)
{
}
});
</script>
HTML/PHP:
<table class="orderForm" id="orderForm" width="100%">
<tr class="row">
<td>
<div class="pure-control-group">
<label>Product or Service</label><select name="product[]" id="product">
<option value=""></option>
<?php while($productRow = mysql_fetch_assoc($productResult)){?>
<option value="<?php echo $productRow['prouct_id'];?>" data-price="$<?php echo $productRow['price']; ?>"><?php echo $productRow['product']; ?></option>
<?php } ?>
</select>
</div>
<div class="pure-control-group">
<label>Price</label><input type="text" id="price" name="price[]">
</div>
<input type="button" class="deleteThisRow" id="deleteThisRow" value="Delete"/>
</td>
</tr>
</table>
<input type="button" id="btnAddMore" value="Add Product or Service" class="pure-button"/>
.clone() by default doesn't clone the event handlers. You can use .clone(true).appendTo(".orderForm");. The true parameter of the .clone() function copies the values and events over as well.

PHP AJAX within a table

I have a table that lists my students.. and the License Number Column will either shown the license number or if there is no number in the DB it will show a textbox..
Upon submit (note: no submit button, to keep it need i just press return)
The results from the PHP script will be shown via Ajax.
My complete code is here.
http://pastebin.com/9k0EKXA9
Here is the code within the license number cell on each row:
<td><?php // check if license number exists.
if($row['license_no'] == '')
{
//show form.
?>
<form method="POST" id="license_no_update"">
<input type="text" name="license_no" value="License Number" />
<input type="hidden" value="<?php echo $row['student_id']; ?>" name="student_id" />
</form>
<div id="output"></div>
<?php
}else{
//show license no.
echo $row['license_no'];
}
?></td>
Here Is the JQUERY
<script type="text/javascript">
$(document).ready(function() {
$("#license_no_update").submit(function() {
var license_no_update = $(this).serialize();
$.post('license_update.php', license_no_update, function(data) {
// We not pop the output inside the #output DIV.
$("#output").html(data);
});
return false;
});
});
</script>
The problem i am having, even after searching google many times..
I know i have to have a new form & element id for each row of the table.
but even when i do have those, i do not know how to get JQUERY to find that unique number..
currently with the code attached if i submit on the first row of the table, the correct results are displayed, if i submit on any other row nothing is displayed..
I hope that all makes sense.
Regards
Aaron
Use .find() to find the value of the hidden input within the clicked form. Notice the use of $(this) which is the form itself, and then you can narrow down the input by it's name, since you know the name.
However, it is unclear what you want to do with the id so I left that up to you.
$("#license_no_update").submit(function() {
var studentID = $(this).find("input[name='student_id']").val();
var license_no_update = $(this).serialize();
$.post('license_update.php', license_no_update, function(data) {
// We not pop the output inside the #output DIV.
$("#output-" + studentID).html(data);
});
return false;
});
Update:
Here is one way of creating unique ID's for each output:
if($row['license_no'] == '')
{
//show form.
?>
<form method="POST" id="license_no_update"">
<input type="text" name="license_no" value="License Number" />
<input type="hidden" value="<?php echo $row['student_id']; ?>" name="student_id" />
</form>
<div id="output-<?php echo $row['student_id']; ?>"></div>
<?php
}else{
//show license no.
echo $row['license_no'];
}

Editing a html table using jquery,php and saving records to mysql

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();
});
});

How to change number values in PHP when radio button is check or click

I have 4 rows in a table.
Each row has 4 radio buttons.
Each radio buttons has value number [1, 2, 3, 4]
When user selects one of the radio buttons, it automatically prints the value in each row. Then I take each value and total them at the bottom of the table.
I'm guessing it can be done with javascript? But how?
Here's a sample PHP code for the row:
<input type="radio" name="a" value="1" <?php if($row['a'] == '1'){echo "checked";} ?>/>
I want to print out the value at the end of each row. Then total the each row's value at the bottom of the table.
Also, here's my php code to total all rows.
$total = $a + $b + $c + $d;
echo $total;
?>
Thanks! :)
Though I can't post any code at the moment (dehabilitating numeric keypad), the general method to dynamically update content dependent on a backend is to activate an AJAX call (or page refresh) whenever a checkbox's state is changed. The new state and/or unique parameters will be sent to your server, which will then echo (as per your request) out the new view.
From the information you've provided, it is difficult to determine whether the radio buttons dependend on any special backend model (database information).
If they are not, then we will assume that the checkboxes have unique IDs, prefixed with chk_, and that the text box you want to output the value to is called out. We will also assume that you are using jQuery.
var total = 0;
for (var i = 1; i <= 4; i++)
{
var e = $('#chk' + i);
if (e.is(':checked'))
{
total += parseInt(e.val());
}
}
$("#out").text(total);
EDIT: After the edit of your original post, this code is still valid. However, if you name your checkbox a like you have, you will need to revise the for loop in the above code. You may be able to loop through all radio buttons, or radio buttons inside a certain HTML element. The implementation is up to you.
All the calculations should made on client side as per your scenario. So in this case JavaScript will do the work.
Below code will calculate each row as per radio selection and also calculate total of all selections.
<html>
<head>
<script language="JavaScript">
<!--
function calculateRow(val1, val2)
{
var total = 0;
var ctr=1;
var divs=document.getElementsByTagName('div');
document.getElementById('selectedValue_'+val2).innerHTML = val1.value;
for(i=0;i<divs.length;i++)
{
divId = divs[i].id.substring(0,14);
if(divId == 'selectedValue_')
{
total += parseInt(document.getElementById('selectedValue_'+ctr).innerHTML);
ctr++;
}
}
document.getElementById('total').innerHTML = total;
}
//-->
</script>
</head>
<body>
<form name="frmScore">
<table border=1>
<tr>
<td>Select</td>
<td>Score</td>
</tr>
<?php
for($i=1;$i<=10;$i++)
{
echo "
<tr>
<td>
<input type='radio' value='1' name='test{$i}' onclick='calculateRow(this,{$i})'>
<input type='radio' value='2' name='test{$i}' onclick='calculateRow(this,{$i})'>
<input type='radio' value='3' name='test{$i}' onclick='calculateRow(this,{$i})'>
<input type='radio' value='4' name='test{$i}' onclick='calculateRow(this,{$i})'>
</td>
<td><div id='selectedValue_{$i}'>0</div></td>
</tr>";
}
?>
<tr>
<td>Total</td>
<td><div id='total'></div></td>
</tr>
</table>
</form>
</body>
</html>
Cheers!!!

Categories