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
Related
I have a form with dynamic inputs, in this case, I take a car owner with multiple cars, so for the same person/client I need to save several cars with the brand name and year model:
<form action="save.php" method="post">
<label for="name">Name of owner</label>
<input type="text" name="name" id="name">
<div class="field_wrapper"> <!--wrapper that help me in the javascript button-->
<label for="car_model">Brand name</label>
<select name="car_model[]" id="car_model">
<option value="ford">Ford</option>
<option value="honda">Honda</option>
<option value="chevrolet">Chevrolet</option>
</select>
<label for="year">Year</label>
<input type="number" name="year[]" id="year">
<input type="button" class= "add_button" value="+" onClick="javascript:void(0);" title="add fields" style="width:25px"></td>
</div>
</form>
I don't know how many cars he/she have, so I used this javascript for add and remove input fields with jQuery:
<script type="text/javascript">
$(document).ready(function(){
var maxField = 5; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><label for="car_model">Brand name</label><select name="car_model[]" id="car_model"><option value="ford">Ford</option><option value="honda">Honda</option><option value="chevrolet">Chevrolet</option></select><label for="year">Year</label><input type="number" name="year[]" id="year"><input type="button" class= "remove_button" value="-" onClick="javascript:void(0);" title="remove field" style="width:25px"></div>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
} else{
alert('you reach the limit')
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
What is my goal? in some cases I will have multiple inputs for the same "name" value, So I save the brand name as a array car_model[] and year[].
I understand that I must save in my save.php something like this:
$name=$_POST['name'];
$array_car=$_REQUEST['car_model'];
$array_year=$_REQUEST['year']
Here comes the problem: how do I save that in my database? I try with a foreach but looks like is not the rigth way to do it.
Note: I know how to save a "regular" form, I mean, it would be something like:
$query="INSERT INTO cars ('name','car_model','year') VALUES ('$name','$car_model','$year')";
and variables should be:
$name=$_POST['name'];
$car_model=$_POST['car_model'];
$year=$_POST['year'];
but, what about this time?
thanks for help, and I hope this time I explain what I need on a better way
First, save each array and values that you receive from POST
$name=$_POST['name'];
$array_car=$_REQUEST['car_model'];
$array_year=$_REQUEST['year'];
use sizeof() to measure the array size and save it to a variable, no matter which one because both will have the same size:
$size=sizeof($array_car);
then use a for loop limit by the size, and finally, the code will look like this:
<?php
include 'conexion.php';
$name=$_POST['name'];
$array_car=$_REQUEST['car_model'];
$array_year=$_REQUEST['year'];
$size=sizeof($array_car);
for($i=0;$i<$size;$i++){
$query="INSERT INTO cars (owner,brand,year) VALUES ('$name','$array_car[$i]','$array_year[$i]')";
if (mysqli_query($conn, $query)) {
} else {
echo "Error: " . $query . "<br>" . mysqli_error($conn);
}
}
mysqli_close($conn);
?>
I need to Multiply two user Input Fields and show the results in the third field. The Result field must change when either of the User Input fields are changed.
<input type="number" name="rate" id="rate" />
<input type="number" name="box" id="box" />
The result should be in a third field which changes when either of the two above fields is changed. This totally depends on the user input
<input type="number" name="amount" id="amount" readonly />
I need to do this Multiplication with Jquery.
Thanks in advance
Try this : bind change event listener for rate and box input box and inside it multiply the values to put it in amount input.
$('#rate, #box').change(function(){
var rate = parseFloat($('#rate').val()) || 0;
var box = parseFloat($('#box').val()) || 0;
$('#amount').val(rate * box);
});
DEMO
You can use keyup event to calculate amount as soon as you enter other fields
$('#rate, #box').keyup(function(){
var rate = parseFloat($('#rate').val()) || 0;
var box = parseFloat($('#box').val()) || 0;
$('#amount').val(rate * box);
});
DEMO
Try this : bind input event listener on rate and box input box and inside it multiply the values to put it in amount input.
The input event only fires when the value of the input has changed whereas change only fires once the field has lost focus. input fires immediately
$('#rate, #box').on('input',function(){
var rate = parseFloat($('#rate').val()) || 0;
var box = parseFloat($('#box').val()) || 0;
$('#amount').val(rate * box);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="number" name="rate" id="rate" value=""/>
<input type="number" name="box" id="box" value=""/>
<input type="number" name="amount" id="amount" readonly />
Here is my 2 cents on the above scenario -
http://jsfiddle.net/ak9ejpne/3/
My aim was to keep the code thin & clean and with some MVC flavor.
function Operand(a,b){
this.a = parseInt(a);
this.b = b;
this.c = (this.a)*(this.b);
this.set = function(key,edit){
this[key] = edit;
this.c = (this.a)*(this.b);
};
return this;
}
Do let me know if it is a useful approach for you :)
You can Try It.
<script type="text/javascript">
$("#txtOne,#txtTwo").on("change keyup", function(e){
var txtOne = parseFloat($("#txtOne").val());
var txtTwo = parseFloat($("#txtTwo").val());
var result = txtOne * txtTwo ;
if (!isNaN(result)) {
$("#txtAmount").val(result);
}
});
</script>
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'];
}
The code below consists of invoice-lines that contain some input fields that the user can fill out. The initial number of input lines is 20. Users will often need to add more lines to the invoice by clicking the "Add lines" button. Every click of this button uses Javascript to append more lines to the invoice.
The problem is when the form gets submitted only the first 20 lines seem to get submitted. All the javascript appended invoice lines are ignored and never POSTed.
I have been trying to work out this problem for quite a while now, I was wondering if someone can guide me as to how to go about implementing this correctly?
Many thanks in advance.
Markup / PHP
<?php
for($i=0; $i < 20; $i++){
echo '
<div class="invoice-line">
<div class="prod-id-cell"><input name="rows['.$i.'][id]" type="text" class="prod-id-input">
<div class="smart-suggestions">
<!-- RESULT SUGGESTIONS WILL POPULATE HERE --> </div>
</div>
<div class="prod-name-cell">
<input type="text" name="rows['.$i.'][name]" class="prod-name-input"/> <div class="smart-suggestions">
<!-- RESULT SUGGESTIONS WILL POPULATE HERE -->
</div>
</div>
<div class="price-cell"><input name="rows['.$i.'][price]" class="price-input" type="text" /></div>
<div class="quantity-cell"><input name="rows['.$i.'][quantity]" type="text" class="quantity-input"></div>
<div class="unit-price-cell"><input name="rows['.$i.'][unit-price]" class="unit-price-input" type="text" /></div>
<div class="num-kits-cell"><input name="rows['.$i.'][num-kits]" class="num-kits-input" type="text" /></div>
<div class="amount-cell"><input name="rows['.$i.'][amount]" class="amount-input" type="text" readonly="readonly" /></div>
</div>';
}
?>
Javascript
//**ADD 5 LINES**//
$('.invoice-links div').on("click", ".add-five-trigger", function(){
for(var i=0; i < 5; i++){
var invoiceLine = $(".invoice-line").first().clone( true, true );
$(invoiceLine).insertAfter(".invoice-line:last");
$(".invoice-line:last").find('input').val('').attr('disabled','disabled');
}
});
You forgot to change the name attributes of the cloned inputs. They would overwrite previous fields.
Use this:
var invoiceLine = $(".invoice-line").last();
var newLine = invoiceLine.clone( true, true );
invoiceLine.after(newLine);
newLine.find('input').each(function() {
if (this.type == "text")
this.value = "";
this.name = this.name.replace(/rows\[(\d+)\]/, function(m, num) {
return "rows["+(+num+1)+"]";
});
this.disabled = true;
});
The values are not being posted because you are disabling them. Input elements with disabled attribute don't get posted.
Also, always make sure that elements have unique ids and names. Elements without names don't get posted.
You are not giving new names to the elements you create. You are also disabling them.
$(".invoice-line:last").find('input').val('').attr('disabled','disabled');
Disabled form inputs will never be submitted with the form.
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).