In my case I have lines of radioboxes, every radio has a value. This value must be calculated and the result must be placed in a DIV.
My Problem is, I can't find a way to subtract the value of the choosen radion before.
let me show you a sample markup:
<table>
<tr>
<td><input name="tools" value="20" type="radio"></td>
<td><input name="tools" value="300" type="radio"></td>
<td><input name="tools" value="1000" type="radio"></td>
</tr>
<tr>
<td><input name="addons" value="5" type="radio"></td>
<td><input name="addons" value="10" type="radio"></td>
</tr>
</table>
<div id="result"></div>
JavaScript :
var radioClick = $('input[type="radio"]');
radioClick.on('change', function(evt){
// function sub or add the price...
// here is a shortcut of the add calc version...
var price = $(this).val(),
showPrice = $('#result').text(),
endresult = parseFloat(showPrice) + parseFloat(price),
$('#result').text(endResult);
});
With checkboxes it works fine, but in case of radioboyes I don't have a click-event to identify this on I must subtract.
in the first line we see the radios name=tools. here I take at first this one with value 20.
after that the value 20 will be shown in the#result, fine. But when I take now another radio name=tools the new value will add to the 20. and that is my problem. I don't know how to find the before selected radio button to get this value and subtract it.
Try using this:
html code:
<table>
<tr>
<td><input name="tools" class="test1" value="20" type="radio"></td>
<td><input name="tools" class="test1" value="300" type="radio"></td>
<td><input name="tools" class="test1" value="1000" type="radio"></td>
</tr>
<tr>
<td><input name="addons" class="test" value="5" type="radio"></td>
<td><input name="addons" class ="test" value="10" type="radio"></td>
</tr>
javascript:
<script>
var testPrice = 0;
var test1Price = 0;
var endprice = 0;
var price ='';
$('.test').click(function(){
price = $(this).val();
testPrice = price;
endPrice = parseFloat(testPrice) + parseFloat(test1Price),
$('#result').text(endPrice);
});
$('.test1').click(function(){
var price = $(this).val();
test1Price = price;
endPrice = parseFloat(testPrice) + parseFloat(test1Price),
$('#result').text(endPrice);
});
</script>
try it's demo on http://jsfiddle.net/rxrzX/
You don't need to substract. You can just find 2 value of 2 diff radio button : tools and addons. Then just add them and write in the div
You can get radio button value by :
$('input[name=radioName]:checked').val();
I think try this :
var radioClick = $('input[type="radio"]');
radioClick.on('change', function(evt){
// function sub or add the price...
// here is a shortcut of the add calc version...
var toolsprice = $('input[name=tools]:checked').val(),
var addonsprice = $('input[name=addons]:checked').val(),
endresult = parseFloat(toolsPrice) + parseFloat(addonsprice),
$('#result').text(endResult);
});
You could use an object literal that tracks the value, using a closure:
radioClick.on('change', (function()
{
var valTracker = {},
resultDiv = $('#result');//easier on the DOM
return function(evt)
{
valTracker[this.name] = valTracker[this.name] || 0;//get old value
var endResult = parseFloat(resultDiv.text()) + parseFloat($(this).val()) - valTracker[this.name];//subtract old value, too
valTracker[this.name] = parseFloat($(this).val());//set current value
resultDiv.text(endResult);
}
}()));
The valTracker object literal tracks the current radio value (the name of the element is used as property). I've also kept a reference to the $('#result') div in the closure. That way, you don't have to query the DOM every time the callback function is called.
Try using the code below: JSFIDDLE
var radio_groups = []
$(":radio").each(function(){
if (radio_groups.indexOf(this.name) == -1){
radio_groups.push(this.name);
}
});
$('input:radio').change(function(evt){
var resultPrice = 0;
$.each(radio_groups, function(){
curPrice = $(':radio[name="' + this + '"]:checked').val();
if (!(curPrice)){
curPrice = 0;
}
resultPrice = parseInt(resultPrice) + parseInt(curPrice);
});
$('#result').text(resultPrice);
});
This will work, even if you add more radio button groups. If you want this functionality only for specific groups, define the names in the array radio_groups instead of getting them from the document.
Related
<tbody id="dailysale_tbody">
<tr class="items">
<td><select id="items_select" name="dailysale[luitem_id]"><option value=""></option></select></td>
<td><select id="brands_select" name="dailysale[lubrand_id]"><option value=""></option></select></td>
<td><select id="models_select" name="dailysale[lumodel_id]"><option value=""></option></select></td>
<td><input class="texts" id="dailysale_qty" name="dailysale[qty]" type="text" /></td>
<td><input class="texts" id="dailysale_price" name="dailysale[price]" type="text" /></td>
<td><input class="texts" id="dailysale_total" name="dailysale[total]" type="text" /></td>
<td><input type="checkbox" class="delete_row"></td>
</tr>
$(function() {
$('#dailysale_qty, #dailysale_price').keyup(function() {
var last_item = $('.items').find('#dailysale_qty');
var qty = last_row.find('#dailysale_qty').val();
var price = last_row.find('#dailysale_price').val();
var sub_total = last_row.find('#dailysale_total');
var s_total = qty * price;
if (isNaN(s_total)) {
sub_total.val('0');
}
else
sub_total.val(s_total);
});
});
I am able to perform calculations on this row. However, when I dynamically add rows with jquery, calculations are not working on the other rows.
When the calculating function is bind a button onclick, everything works well. But not on input keyup as required. I want to perform calculations on the new added row with onkeyup on qty and price input fields.
Note than upon cloning, the ids are stripped of the current row and assigned to the new row for reference.
You probably not registering keyup function when you adding new row.
You should do :
$('#dailysale_qty, #dailysale_price').unbind('keyup').keyup( function(...
Every time you adding new row.
#Nosyara The suggested line of code isn't working. Here is how am adding new rows. The commented line is what you suggested.
$(function(){
$('#newitembtn').click(function(){
//$('#dailysale_qty, #dailysale_price').unbind('keyup').keyup(function() {
var last_row = $('#dailysale_tbody').find('tr:last');
var newrow = last_row.clone();
last_row.find('#items_select').removeAttr('id');
last_row.find('#brands_select').removeAttr('id');
last_row.find('#models_select').removeAttr('id');
last_row.find('#dailysale_qty').removeAttr('id');
last_row.find('#dailysale_price').removeAttr('id');
last_row.find('#dailysale_total').removeAttr('id');
newrow.find('#items_select').val('');
newrow.find('#brands_select').val('');
newrow.find('#models_select').val('');
newrow.find('#dailysale_qty').val('');
newrow.find('#dailysale_price').val('');
newrow.find('#dailysale_total').val('');
last_row.after(newrow);
});
});
});
here is my sample code
<table id="accessListTable">
<tr class="ui-grid groupHead">
<td><input type="checkbox" class="groupHeadCheck"/></td>
</tr>
<tr>
<td><input type="checkbox" id="1"/></td>
</tr>
<tr>
<td><input type="checkbox" id="2"/></td>
</tr>
<tr>
<td><input type="checkbox" id="3"/></td>
</tr>
<tr class="ui-grid groupHead">
<td><input type="checkbox" class="groupHeadCheck"/></td>
</tr>
<tr>
<td><input type="checkbox" id="4"/></td>
</tr>
</table>
E.g, When the checkbox in first row with class groupHeadCheck, all the checkboxex of id 1, 2 and 3 will also be checked.
And if all the checkboxes of 1, 2, and 3 are already checked, the checkbox in first row will be checked.
Please any help!
You can add a click handler to the group checkbox then inside the handler you can find its tr element and the tr's next sibling element till the next occurrence of tr.groupHead
$(function ($) {
$(".groupHeadCheck").on("click", function (event) {
$(this).closest('tr').nextUntil('tr.groupHead').find('input[type="checkbox"]').prop('checked', this.checked)
})
});
Demo: Fiddle
I am sure it can be done in a prettier manner, but this is the basic idea:
$("table tbody").on("change", "input[type=checkbox]", function (e) {
var currentCB = $(this);
var isChecked = this.checked;
if (currentCB.is(".groupHeadCheck")) {
var allCbs = currentCB.closest('tr').nextUntil('tr.groupHead').find('[type="checkbox"]');
allCbs.prop('checked', isChecked);
} else {
var allCbs = currentCB.closest('tr').prevAll("tr.groupHead:first").nextUntil('tr.groupHead').andSelf().find('[type="checkbox"]');
var allSlaves = allCbs.not(".groupHeadCheck");
var master = allCbs.filter(".groupHeadCheck");
var allChecked = isChecked ? allSlaves.filter(":checked").length === allSlaves.length : false;
master.prop("checked", allChecked);
}
});
and if you need to run the code to force the check all state
$(".groupHead").next().find("[type=checkbox]").change();
JSFiddle
This would check all if the first is checked (or uncheck all)
$(document).on('click', '.groupHeadCheck',function() {
$(this).closest('tr').nextUntil('tr.groupHead').find('input[type="checkbox"]').prop('checked', $(this).prop('checked'))
});
you could fiddle a bit with your classes (or IDs) to make it right for you
I know this is already answered, but I wanted a more generic way of doing this. In my case, I wanted to check all in a column until I hit a new group. I also had 3 columns with checkboxes. The ones in the first checkbox column all had names starting with "S_", the second "A_" and the third "C_". I used this to pick out the checkboxes I wanted. I also didn't name the heading checkboxes that were used to do the "check all" so it would stop when it hit the next groupings row.
You could use the class name to apply the same logic.
First, here is what a check all checkbox looked like:
<td>
<input type="checkbox" onchange="checkAll(this, 'S_');" />
</td>
Then the javascript function it calls when clicked:
function checkAll(sender, match)
{
var table = $(sender).closest('table').get(0);
var selector = "input[type='checkbox'][name^='" + match + "']";
for (var i = $(sender).closest('tr').index() + 1; i < table.rows.length; i++)
{
var cb = $(table.rows[i]).find(selector).get(0);
if (cb === undefined)
break;
if ($(cb).is(':enabled'))
cb.checked = sender.checked;
}
}
So it will search each subsequent row for a checkbox with the name starting with "S_". Only the checkboxes the user has rights to will be changed. I was going to use $(td).index() to find the right column, but this didn't work out because some rows had colspan's greater than 1.
There are 3 input fields.
Each has its own hidden input which helds value.
At this moment script works only for Bananas.(:-))
1 Banana is worth 1 banana OR 0.5 apple or 0.021 of a cookie(in other words 1 apple = 2 bananas, 46 bananas = cookie, 1 banana = 1 banana).
What I would like this script to do is to calculate values also for Apples and Cookies, and sum them up to show how much are they worth in "other" currencies.(for example show the price of 3 apples and 4 cookies in all 3 currencies)
I do realise that the code is very...well it would be a shame to call it code.
I just don't have any idea how to do it;
Any help would very appreciated.
Fiddle:
http://jsfiddle.net/eN7S6/9/
HTML:
<table>
<tr>
<td>
Apple<input name="inputone" id="inputone" class="calc" value="0"><span id="TotalOne"></span>
</td>
</tr>
<tr>
<td>
Banana<input name="inputtwo" id="inputtwo" class="calc" value="0"><span id="TotalTwo"></span>
</td>
</tr>
<tr>
<td>
Cookie<input name="inputthree" id="inputthree" class="calc" value="0"><span id="TotalThree"></span>
</td>
</tr>
</table>
<input name="multiplierone" id="multiplierone" class="calc" value="1" type="hidden" readonly>
<input name="multipliertwo" id="multipliertwo" class="calc" value="0.5" type="hidden" readonly>
<input name="multiplierthree" id="multiplierthree" class="calc" value="23" type="hidden" readonly>
<input type="button" id="update" value="Calculate" />
JQ:
$(document).ready(function() {
$('#update').click(function() {
var inputone = $('#inputone').val();
var multiplierone = $('#multiplierone').val();
var inputtwo = $('#inputtwo').val();
var multipliertwo = $('#multipliertwo').val();
var inputthree = $('#inputthree').val();
var multiplierthree = $('#multiplierthree').val();
var totalTotalOne = (inputtwo * multipliertwo);
var totalTotalTwo = (inputtwo);
var totalTotalThree = (inputtwo / multiplierthree / 2);
$('#TotalOne').text(totalTotalOne);
$('#TotalTwo').text(totalTotalTwo);
$('#TotalThree').text(totalTotalThree);
});
});
Well from what i gather from you description is that you want to get an amount that you have of a particular item. So if you have 10 bananas you want to calculate those 10 bananas against the other elements. The same goes for if you have 37 cookies you want to know how much its worth against the other items.
I believe that if you were to simplify your UI into two elements one being a input text field to enter amounts and another radio check collection, or it could be a selection field to select what type you have it will make better sense.
In your current setup you are not taking into account that your type(Apple, Banana, cookie) variable will change its only hard-coded to calculate bananas.
I quickly setup a jsbin to show you what i mean. Its just a start that may help you think of something else to do. Happy coding!
http://jsbin.com/EKisiGIK/10/edit
$(document).ready(function() {
$('#update').click(function() {
var inputone = parseFloat($('#inputone').val());
var multiplierone = parseFloat($('#multiplierone').val());
var inputtwo =parseFloat( $('#inputtwo').val());
var multipliertwo = parseFloat($('#multipliertwo').val());
var inputthree =parseFloat( $('#inputthree').val());
var multiplierthree = parseFloat($('#multiplierthree').val());
var totalTotalOne = (inputtwo * multipliertwo);
var totalTotalTwo = (inputtwo);
var totalTotalThree = (inputtwo / multiplierthree / 2);
$('#TotalOne').text(totalTotalOne);
$('#TotalTwo').text(totalTotalTwo);
$('#TotalThree').text(totalTotalThree);
});
});
Try this
One thing that you can do to make this problem simpler is to convert all currencies to a base currency before converting to their respective currencies. Using the example you have given i have converted all the currencies to their Cookie equivalent as it was the most valuable therefore removing the need to work with decimal values.
Change the HTML to
<input name="multiplierone" id="multiplierone" class="calc" value="23" type="hidden" readonly>
<input name="multipliertwo" id="multipliertwo" class="calc" value="46" type="hidden" readonly>
<input name="multiplierthree" id="multiplierthree" class="calc" value="1" type="hidden" readonly>
which is how many of each of the currencies it takes to make up one Cookie.
The following code can then be used to convert the currencies to Cookies
var base_total = inputone / multiplierone + inputtwo / multipliertwo + inputthree / multiplierthree;
var totalTotalOne = (base_total * multiplierone);
var totalTotalTwo = (base_total * multipliertwo);
var totalTotalThree = (base_total * multiplierthree);
this code will convert all the separate input values into their equivalent Cookie value. Once you have a total of all the fields as a cookie value it is a simple matter to convert that value back to all the respective currency values.
Fiddle
i want to iterate through the table rows and get the id and name of each checkbox checked in each tr in the first td and save it in a new Object() called values ex: values.id, values.name
Thanks
<table>
<tr>
<td>
<input id="1" type="checkbox" name="name1" checked="checked">
</td>
<td>
Some input control 1
</td>
</tr>
<tr>
<td>
<input id="2" type="checkbox" name="name2">
</td>
<td>
Some input control 2
</td>
</tr>
</table>
Working example
aRecord is an array of objects with each object containing both the name and ID of each checked checkbox found in the table.
$(document).ready(function() {
var aRecord = [];
$('#your_table input:checkbox:checked').each(function() {
var oChkBox = {};
oChkBox.name = $(this).attr('name');
oChkBox.id = $(this).attr('id');
aRecord.push(oChkBox);
});
var i = aRecord.length;
while (i--) {
alert("Name: "+ aRecord[i].name + " ID: "+ aRecord[i].id);
}
});
http://jsfiddle.net/tracyfu/r6RMV/
var values = {};
$('tr input:checked').each(function(i) {
values[i] = [];
values[i].push($(this).attr('id'));
values[i].push($(this).attr('name'));
});
Will produce:
values = { [1, 'name1'] }
I'm leaving this solution as-is, since you specifically said you wanted to store the values in an object named values, but without knowing what you're going to do with the data, I would store the values in an array instead...
I have a table and want to calculate each element like:
calc-this-cost * calc-this-cost(value of checkbox) = calc-this-total
Then summ all calc-this-cost and put it to totalcost div.
This is table:
<td class="params2">
<table id="calc-params">
<tr>
<td>aaa</td><td class="calc-this-cost">159964</td><td class="calc-this-count">
<input type="checkbox" name="a002" value="0" onclick="calculate(this);" />
</td><td class="calc-this-total">0</td>
</tr>
<tr>
<td>bbb</td><td class="calc-this-cost">230073</td><td class="calc-this-count">
<input type="checkbox" name="a003" value="0" onclick="calculate(this);" />
</td><td class="calc-this-total">0</td>
</tr>
<tr>
<td>ccc</td><td class="calc-this-cost">159964</td><td class="calc-this-count">
<input type="checkbox" name="a004" value="1" onclick="calculate(this);" />
</td><td class="calc-this-total">0</td>
</tr>
........
</table>
.......
</td>
<div id="calc-total-price">TOTAL COST: <span>0</span></div>
My script (in function calculate)
var totalcost=0;
$('.params2 tr').each(function(){
var count=parseFloat($('input[type=checkbox]',$(this)).attr('value'));
var price=parseFloat($('.calc-this-cost',$(this)).text().replace(" ",""));
$('.calc-this-total',$(this)).html(count*price);
totalcost+=parseFloat($('.calc-this-cost',$(this)).text());
});
$('#calc-total-price span').html(totalcost);
Counting each element and put result to calc-this-cost - work perfect.
But totalcost result NaN. Why?
[general] don't parseFloat() more than you need to
[general] move repeating code to functions
[jQuery] use .find() over context and cache nodes ($row)
[general] look at how String.replace() works
[general] look at Number.toFixed() for displaying floats
example
var totalcost = 0,
toFloat = function(value) {
// remove all whitespace
// note that replace(" ", '') only replaces the first _space_ found!
value = (value + "").replace(/\s+/g, '');
value = parseFloat(value || "0", 10);
return !isNaN(value) ? value : 0;
};
$('.params2 tr').each( function() {
var $row = $(this),
count = toFloat($row.find('.calc-this-count input').val()),
price = toFloat($row.find('.calc-this-cost').text()),
total = count * price;
$row.find('calc-this-total').text(total.toFixed(2));
totalcost += total;
});
$('#calc-total-price span').text(totalcost.toFixed(2));
console.log() will solve all your problems:
$('.params2 tr').each(function(){
var count=parseFloat($('input[type=checkbox]',$(this)).attr('value'));
var price=parseFloat($('.calc-this-cost',$(this)).text().replace(" ",""));
$('.calc-this-total',$(this)).html(count*price);
totalcost+=parseFloat($('.calc-this-cost',$(this)).text());
console.log(count, price, totalcost)
});
Add more logging where every you don't understand something. Didn't I just tell you to use logging? :)