I have the following functionality I would like to build into a form using jQuery:
I have a list of values:
Invoice No: 110, Amount: 240.00
Invoice No: 111, Amount: 399.00
Invoice No: 112, Amount: 150.00
Next to each row there is a checkbox which is set to checked by default. Right at the bottom there is a textbox with the total 789.00 for the set of data. I would like to update the textbox when one of the checkboxes are de-selected & selected with the total of invoice amounts which checkboxs are checked.
The form will then be submitted to itself with the value of the textbox set.
Any suggestions welcome, as I'm a noob with jQuery.
Just answered similar question here: jQuery - Getting total depending on which checkboxes are selected
put some css class to your invoice total span, ex: <span class="inv-total">120<span>.
then put your checkbox inside of your invoice <div>:
<div>
<input type="checkbox" value="##inv if here ##" />
</div>
and then jQuery of course:
$(document).ready(function() {
$("input[type=checkbox]").click(function(event) {
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).parent().find('.inv-total').text().substring(1));
});
if (total == 0) {
$('#total').val('');
}
else {
$('#total').val('$' + total);
}
});
});
I haven't chanse to test it, but this is the idea.
Live example: http://jsfiddle.net/dH9Eb/2/
$('.checkbox').change(function () {
var text-box-val = $('.textbox').val();
if ($(this).attr("checked")) {
var new-val = $('.textbox').val() + $(this).attr('value');
$('.textbox').val(new-val);
}
else {
var new-val = $('.textbox').val() - $(this).attr('value');
$('.textbox').val(new-val);
}
});
Here is a solution with html table to update amount when you click on a checkbox:
HTML:
<table id="invoices">
<thead>
<tr>
<td>Invoice no</td>
<td>Total</td>
<td>include</td>
</tr>
</thead>
<tbody>
<tr>
<td class="invoiceId">112</td>
<td class="amount">10</td>
<td><input class="amountCheck" type="checkbox" checked="checked"/></td>
</tr>
</tbody>
</table>
jQuery:
$("#invoices .amountCheck").click(function() {
var amount = parseInt($(this).closest("tr").find(".amount").text());
if ($(this).is(":checked")) {
total += amount;
} else {
total -= amount;
}
$("#invoiceTotal").val(total);
});
Don't forget to check if the total is correct on server side.
Working solution : jsFiddle
Related
Okay so I have a radio button on which my variable values get change through java-script.I am displaying that changed value in <h>Tag right.
Now I wants to post this <h> Tag value into database. I know <h>Tag is not a form element and other solution is using hidden input tag.
Here is my HTML Code:
<label><input type="radio" name="optradio" id="delivery1" value="normal" checked><span class="label label-success">Regular Delivery</span></label><label>If you choose regular Delivery, it will take atleast 4 days time to deliver your product.(There will be no extra charges applied)</label>
<label><input type="radio" name="optradio" id="delivery2" value="fast"><span class="label label-danger">One Day Delivery</span></label>
<label>If you choose One Day Delivery, product(s) will be delivered to you in 24 hours. (40 Rs Will be charged extra.) </label>
JS for that:
<script type="text/javascript">
$(document).ready(function(){
$('#delivery1,#delivery2').change(function(){
price = $('#price').text();
finals = $('#finals').text();
finals1 = $('#HIDDENPRICE').text();
if($('#delivery2').is(':checked')) {
price = (price)*1 + 40;
finals=price;
finals1=price;
} else {
price = (price)*1 - 40;
finals=price;
finals1=price;
}
$('#price').text(price);
$('#finals').text(price);
$('#HIDDENPRICE').text(price);
});
});
</script>
Displaying the value from radiobutton:
<h5><strong>Total</strong>
<h5 id="price" name="finalprice">
<?php
$finalprice=$item_total;
echo $finalprice;
?>
</h5>
</h5>
Now I want this Tag value to be posted in database. Any Solution?
Try with a hidden input field :
Look at this.
$(document).ready(function(){
$('#delivery1,#delivery2').change(function(){
price = $('#price').text();
if($('#delivery2').is(':checked')) {
price = parseInt(price) + 40;
} else {
price = parseInt(price) - 40;
}
$('#price').text(price);
$('#final_price').val(price);
});
});
https://jsfiddle.net/rijink121/5vcvt527/4/
You can use the ajax call for this.
$("button").click(function(){
$.post("test_post.php",{ finalprice: 'your final price',},
function(data){
alert(data); // the return data on success
});
});
In the test_post.php you can write the database operation and also you can get the value in the post variable like
$_POST['finalprice']
I would like to sort a table with data row from MySQL then change the order and submit it.
I used jQueryUI.sortable to make those tr tag (row) draggable.
But when I submitting the form, some of them didn't changed order.
Why? I tried to figure it out, I var_dump the data I submitted and I found a problem:
The tr tag (row) I moved from the original order, won't pass to PHP so var_dump will not show the row ID.
To make it easier to understand, I post my code here:
HTML Code
<table>
<thead>
<tr>
<th>Subject</th>
<th>Content</th>
</tr>
</thead>
<tbody id="sortable">
<tr>
<td>
Hello World
<input name="displayorder[]" type="hidden" value="1" />
</td>
<td>I come from Mars!</td>
</tr>
<tr>
<td>
Hello Mars
<input name="displayorder[]" type="hidden" value="2" />
</td>
<td>I come from Jupiter!</td>
</tr>
<tr>
<td>
Hello StackOverflow
<input name="displayorder[]" type="hidden" value="3" />
</td>
<td>I come from North Korea ...</td>
</tr>
</tbody>
<tbody>
<tr>
<td colspan="2"><input type="submit" value="Submit!" />
</tr>
</tbody>
</table>
I omitted the form content cause it is not important
JavaScript (Sortable Library loaded)
$(document).ready(function() {
$('#sortable').sortable({
helper: fixHelper,
axis: 'y',
opacity: 0.6,
}).disableSelection();
});
var fixHelper = function(e, ui) {
ui.children().each(function() {
$(this).width($(this).width());
});
return ui;
};
PHP
$displayorder = $_POST["displayorder"];
if($displayorder != "") {
$order = 1;
foreach($displayorder as $value) {
mysql_query("UPDATE message SET displayorder=$order WHERE announcementid=$value");
$order++;
}
}
I will prefer not using Ajax to do this because I have dozens of similar page to do the same task.
Thanks in advance.
Well I decided to code it every page.
The code now:
JavaScript
$(document).ready(function() {
$('#sortable').sortable({
helper: fixHelper,
axis: 'y',
opacity: 0.4,
update: function(event, ui){
var data = $(this).sortable('serialize');
$.ajax({
data: data,
type: 'POST',
url: '/update.php?action=displayorder'
});
},
}).disableSelection();
});
var fixHelper = function(e, ui) {
ui.children().each(function() {
$(this).width($(this).width());
});
return ui;
};
PHP
foreach($_POST["displayorder"] as $i => $value) {
mysql_query("UPDATE message SET displayorder=$i WHERE announcementid=$value");
$i++;
}
Due to dianuj's great help I solved my Ajax looping issue yesterday.
Click here!
The solution helps me to send and get quantity variable (class="qty") every time I change the number in the input area.
Now I want to revise my Ajax and PHP loop a little bit to get the "total" variable (the quantity * the price).
I try to get the "price" variable by puting an "hidden" input area with price values.(please see the following script attached).The script get the variable of quantity (class="qty") and price (class="price") without problem.
However, when I put different quantity the script only picks the very first price and multiplies my changed quantity number.
For example, I have three items in the function with three differnt prices:
1. apple $1 x1
2. orange $10 x3
3. banana $2 x4
the script result will show $1 * (2+3+4) instead the correct $1*2+$10*3+$2*4
(the ajax script still gets the variable of price and quantity without problem).
My Ajax and PHP loops are as follows, it seems they can get and send the qty and price variable without problem (but only the fixed price of the very first item):
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseleave( function() {
//get qty value and price value from the loop
var totalVal =0;
$( ".qty" ).each(function() {
totalVal += ($(this).val()*$(".price").val());
});
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: {
//sent the total variable to php script (xml)
total : totalVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('total').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
</head>
<body>
<div id="display">
<form action="sessionCartUpdate.php">
<table width="780" border="0" align="center" cellpadding="4" cellspacing="0">
<?php
foreach( $_SESSION["psn"] as $i => $data ){
?>
<input type="hidden" name="psn" value="<?php echo $_SESSION["psn"][$i];?>">
<tr>
<td bgcolor="#CCCCCC" font color="black"><?php echo $_SESSION["psn"][$i];?></td>
<td bgcolor="#CCCCCC"><?php echo $_SESSION["pname"][$i];?></td>
<td bgcolor="#CCCCCC"><?php echo $_SESSION["price"][$i];?></td>
<td bgcolor="#CCCCCC"><input type="text" class="qty" name="qty[]" value="<?php echo $_SESSION["qty"][$i];?>"></td>
<input type="hidden" class="price" value="<?php echo $_SESSION["price"][$i];?>" >
<td bgcolor="#CCCCCC"><input type="submit" name="btnUpdate" value="update" />
<input type="submit" name="btnDelete" value="delete" />
</td>
</tr><br />
<?php
}
?>
<tr><td colspan="5" align="center">the total:<div id="result" class="box" style="height=350px;"></div><div id="result1" class="box" style="height=350px;"></div>
<div id="result2" class="box" style="height=350px;"></div></td></tr>
</table>
</form>
I also include my php script as follows serving as xml for the ajax script above:
<?php
// XML
header("Content-Type: text/xml");
header("Content-Type:text/html; charset=utf-8");
//get total value ("qty * price") from the ajax
$total = (isset($_POST["total"]) ) ? $_POST["total"] : $_GET["total"];
echo "<?xml version=\"1.0\" ?>";
echo "<caculation>";
echo "<total>" . $total . "</total>";
if ($total==0)
echo "<caution>"."please put number!"."</caution>";
else if ($total<=500)
echo "<caution>"."You should buy more!"."</caution>";
echo "";
echo "</caculation>";
?>
I would be very grateful you could offer invaluble advice to help me fix the above bug!
There is a problem the .each loop is for qty not for the price so it is picking the first price because the loop is for qty not for the price you should do something like this
<script language="JavaScript">
$(document).ready(function() {
$("form").mouseleave( function() {
//get qty value and price value from the loop
var totalVal =0;
$( ".qty" ).each(function(i) {
totalVal += ($(this).val()*$(".price:eq("+i+")").val());
});
// get
$.ajax({
type: 'GET',
url: 'getSunBody.php',
data: {
//sent the total variable to php script (xml)
total : totalVal,
},
success: function(data) {
// get XML value
$('#result').html($(data).find('total').text());
$('#result1').html($(data).find('caution').text());
}
});
return false;
});
});
</script>
Use the index of .each loop and get the price placed at that index i have used the jquery selector :eq(index here) and i believe there will be price value for each quantity
I haven't confirmed the following code, but it should at least get you on the right track
var totalVal =0;
$('.qty').each(function() {
var price = $(this).closest('tr').find('.price').val();
totalVal += ($(this).val()*price);
});
UPDATE
I am using jQuery 1.10.1... so .live is depreciated... I just replaced
$("table.dynatable button.remove").live('click', function (e) {
$(this).parents("tr").remove();
});
with
$(document).on("click", "table.dynatable button.remove", function() {
$(this).parents("tr").remove();
});
And now it works, hope this helps someone.
I have this jQuery working with php and html form:
my php:
foreach ($matric_type as $row) {
$matric_type = $row->matric_type;
}
This populates a dropdown depending on the type of matric(grade 12) certification you have.
each matric cerification has a list of different subjects being populated in another dropdown.
my jQuery:
$(document).ready(function () {
var id = 0;
event.preventDefault();
// Add button functionality
$("table.dynatable button.add").click(function (e) {
e.preventDefault();
id++;
var master = $(this).parents("table.dynatable");
// Get a new row based on the prototype row
var prot = master.find(".prototype").clone();
prot.attr("class", "")
prot.find(".id").attr("value", id);
master.find("tbody").append(prot);
});
// Remove button functionality
$("table.dynatable button.remove").live('click', function (e) { // this might be the problem?
//e.preventDefault(); //this does not work
// e.stopImmediatePropagation(); //this does not work
// e.stopPropagation(); //this does not work
$(this).parents("tr").remove();
//$(this).closest('.prototype').remove()
// $(this).parent().parent().remove();
});
});
html:
<table class="dynatable">
<thead>
<tr>
<th>Subject No</th>
<th>Subject</th>
<th>Mark</th>
<th><button class="add">Add</button></th>
</tr>
</thead>
<tbody>
<tr class="prototype">
<td><input type="input" name="id[]" value="0" class="id" readonly /></td>
<td><select id="list"></select></td>
<td><input type="text" name="mark[]" value="" /></td>
<td><button class="remove">Remove</button>
</tr>
</table>
This jQuery uses the add button to add a row with the subject number, a dropdown with subjects, a text field to enter marks for that subject. I can add just fine.. The problem comes with the remove button.. each time I click the remove button it refreshes the page, and adds
?id%5B%5D=0&mark%5B%5D=&id%5B%5D=1&mark%5B%5D=
to the url. The more "subjects" I add the longer the above gets eg. if I add 2 subjects
?id%5B%5D=0&mark%5B%5D=&id%5B%5D=1&mark%5B%5D=&id%5B%5D=2&mark%5B%5D=
I have tried adding to the remove function:
e.preventDefault();
e.stopImmediatePropagation();
e.stopPropagation();
But it still reloads the page, removing all subject rows instead of just the one that is clicked.
Can someone please help by giving a possible solution to my problem?
add the type=button to your button, otherwise button acts like a submit button
<button class="remove" type='button'>Remove</button>
i am passing the class and id of chechboxes to the js function and try to make it dynamic to work for id and class of any checkbox to check all and uncheck all check boxes
here is the html
<input type="checkbox" name="reply_status[]" <?=$checked;?> class="memebers" value="<?=$status[$e]['mail_sent_id']?>">
</td>
<td>
<input type="checkbox" name="send_invoice[]" <?=$checked_send_invoice;?> class="send_invoice" value="<?=$status[$e]['mail_sent_id']?>">
</td>
<td>
<input type="checkbox" name="invoice_paid[]" <?=$checked_invoice_paid;?> class="invoice_paid" value="<?=$status[$e]['mail_sent_id']?>">
</td>
<td>
<input type="checkbox" id="check_all_re" name="check_all" onclick="checkall_members('memebers','check_all_re')">
Check All
</td>
<td>
<input type="checkbox" id="check_all_sv" name="check_all" onclick="checkall_members('send_invoice','check_all_sv')">
Check All
</td>
<td>
<input type="checkbox" id="check_all_ip" name="check_all" onclick="checkall_members('invoice_paid','check_all_ip')">
Check All
</td>
and here is the js function
<script type="text/javascript">
function checkall_members(chechboxclass, chechboxid) {
// var id = document.getElementById("check_all");
alert();
chechboxid = $('#' + chechboxid);
chechboxclass = $('.' + chechboxclass);
if (chechboxid.checked) {
chechboxclass.attr('checked', 'checked');
}
else {
chechboxclass.removeAttr('checked');
}
}
any help would be appreciated
Replace your if..else block with the following.
chechboxclass.prop('checked', chechboxid.prop('checked'));
By the way, it's checkbox and not chechbox.
To improve your code even more, get rid of the inline events:
$('input[name="check_all"]').on('change', function() {
$($(this).data('toggleAll')).prop('checked', this.checked);
});
Now you just need to add data-toggle-all=".send_invoice" etc. to those checkboxes. The param value should be the selector of the checkboxes you want to toggle with that checkbox.
If you have all the name="check_all" elements a class, you could also speed up the selector by using input.whatever_class instead of input[name="check_all"]
i have sorted out the simplest solution for my problem that is
<script type="text/javascript">
function checkall_members(chechboxclass, chechboxid) {
var checkbox = document.getElementById(chechboxid);
chechboxclass = $('.' + chechboxclass);
if (checkbox.checked) {
chechboxclass.attr('checked', 'checked');
}
else {
chechboxclass.removeAttr('checked');
}
}
</script>
i have to get the id elememt within same library of javascript thats why it was not working
var checkbox = document.getElementById(chechboxid);
thanks guys for helping me