Product price calculator isn't working - javascript

I'm creating an order form in which users can select an amount of products and it should immediately change total prices. I made some HTML markup and jquery code to achieve this, but I can't get it working. Can anyone see what I'm doing wrong?

Fixed script:
$("input[type=number]").change(function () {
var value = parseFloat($(this).attr("title"));
var total = (value * this.value).toFixed(2);
if (total < 0) total = 0;
$(this).parent().next().find("input").val('€' + total);
});
Inside of event handler this refers to HTMLInputElement, not jQuery instance so you have to wrap it in $(this).
Also you need to traverse one level up to the parent node and then use next() to get target input field.
Finally I added basic validation to prevent negative prices. You can also add min="0" attribute to input fields.
Demo: http://jsfiddle.net/dfsq/X33pS/

Related

Jquery each loop showing first value as zero or NaN

I am using jquery to gather data from a dynamically created table via Jquery. I am able to get the data, but now I want to sum up the fields and put the result inside a text field or label etc dynamically when I press enter. I am using the following code:
$("#iq").keypress(function(e)
{
if(e.which==13)
{
var tot=0;
$('#tab .itemtotal').each(function()
{
tot = tot + parseInt($(this).html());
});
$("#totalamount").val(tot);
}
});
My problem is that the value showing in the textfield is zero or NaN for the first time and after that its calculating correctly. I used the same code and associating it with a button and checking its click event and its working properly and showing first item also.
Any suggestions? If need some more clarification let me know. Thanks in advance.

jQuery: Put dynamically generated input values to span/div

I'm trying to create form for printing with dynamically generated inputs.
Contents of the fields is shown later in PreviewDiv.
It works fine as long as I specify where they should be, for example:
$('#Prw_CapacityA_1').text($('#CapacityA_1').val());
$('#Prw_CapacityB_1').text($('#CapacityB_1').val());
$('#Prw_CapacityC_1').text($('#CapacityC_1').val());
But if the user creates 100 fields this would be a lot of code to write.
There must be other methods to fix this dynamically, for example:
$('#Prw_CapacityA_'+ counter).text($('#CapacityA_'+ counter).val());
Here's the js fiddle
You could try using attribute starts with selector to select the elements starting with the specific id's and then loop through them using the each() function.
There is no need to have html within your preview table. You can generate it when the user clicks on preview. Modified fiddle
$('#PreviewButton').click(function(){
var capB = $('td input[id^=CapacityB_]');
var capC = $('td input[id^=CapacityC_]');
var table = $("#AddFieldsToPreviewDiv");
table.empty(); //build table everytime user previews so that previously appended values are removed
table.append('<tr><td>ID</td><td>Text 1</td><td>Text 2</td><td>Text 3</td></tr>');
$('td input[id^=CapacityA_]').each(function(i){
table.append('<tr><td>#'+(i + 1)
+'</td><td>'+$(this).val()
+'</td><td>'+$(capB[i]).val()
+'</td><td>'+$(capC[i]).val()
+'</td></tr>');
});
// Show PreviewDiv and hide FormDiv if PreviewButton clicked
$('#PreviewDiv').show();
$('#FormDiv').hide();
});
You could try giving them a unique class (Normally I'd suggest ID but you're using one) say a class of "getinfo"
You could then try the .each() function
https://api.jquery.com/each/
$( ".getinfo" ).each(function( index ) {
var text = $(this).val();
alert(text);
});
This will make an alert box for every element it finds with the class 'getinfo' and then retrieve the value and display it, I hope this gives you a better idea.
If the amount of inputs can change from one page load to the next then you need to use a loop, rather than pulling all the values by 'hand', More code will help better understand what you're trying to achieve and from what.

How do I count the number of select lists with selected values using JQuery?

I am creating the mobile version on a current Rails app with a "quiz" feature. There is currently a count of how many questions you have answered being generated by this function.
function updateGroupProgressCounter($group){
var count = $group.find('tr').has('input:checked').length;
$group.parents('.carousel').find('.checkedCount').text( count);
}
I am changing the inputs from radio buttons to select boxes for mobile and want to keep the count feature but can't quite make it work so far. I've tried
var count = $group.find('tr').has('select option:selected').length;
but gives me the total number of questions in that group. Any help is appreciated.
I would toggle a class on the row based on select change event, then count those rows.
$('tr select').change(function(){
$(this).closest('tr').toggleClass('answered', $(this).val()!='' );
});
Second argument of toggleClass determines whether to add/remove.
Then to get total rows:
$('tr.answered').length
toggleClass() API Docs
Another approach using filter() to count select that have value
var number_answered=$('tr select').filter(function(){
return $(this).val !='';
}).length
Probably you are looking for something like this:
$("#boxes").on("change","input", function(){
$("#total").val($("#boxes input:checked").length);
});
Play around with the fiddle
Considering the value of first element of your select list is empty(i.e "")
So the code will be
var count = 0;
$group.find('tr select').each(function(){
if(this.value.length)
count++;
});
I know this is not the best way to do it.
Adding and removing class on the basis of selection and finally finding the length of element that contains required class would be better approach as suggested by #charlietfl.

Calculating row totals in form using dynamically added rows

I'm creating a form to input an invoice with dynamically added rows (as seen in this image)
I'm using jquery 1.6.2 to calculate Line Total, sum all Line Totals, calculate Tax and display Total. The problem that I'm having is that calculating Line Total only works for the first added row. As you can see on the image above, the first row (Item 1), is fine (2*30=60), but the second row (Item 2) shows the same total as the first one (it should be 4*100=400). Here's the code for this part:
<script type="text/javascript">
var $k = jQuery.noConflict();
$k(function (){
$k('#item_form').live("keyup", "input[name^=linetotal]", function() {
var quantity = $k('input[name^=quantity]').val();
var unitprice = $k('input[name^=unitprice]').val();
$k('input[name^=linetotal]').val(quantity*unitprice);
var sum = $k('input[name^=linetotal]').sum();
$k('#subtotal').val(sum);
$k('#tax').val(Math.round(sum*10*100)/100);
$k('#total').val(Math.round((sum+Math.round(sum*10*100)/100)*100)/100);
});
});
</script>
Any ideas about what should I try? Thank you all!
You are using $k(input[name^=quantity]').val(); to grab the quantity/unitprice, but this grabs all quantity/unitprice inputs, and .val() gets the value of the first one.
You need to get the one on the same line, although it is odd that you are waiting for keyup on the linetotal. Wouldn't you want keyup on quantity and unitprice?
$k('input[name^=quantity], input[name^=unitprice]').live("keyup", function() {
var quantity = parseFloat($k(this).parent().find('input[name^=quantity]').val());
var unitprice = parseFloat($k(this).parent().find('input[name^=unitprice]').val());
$k(this).siblings('input[name^=linetotal]').val(quantity*unitprice);
var sum = $k(this).siblings('input[name^=linetotal]').sum();
$k('#subtotal').val(sum);
$k('#tax').val(Math.round(sum*10*100)/100);
$k('#total').val(Math.round((sum+Math.round(sum*10*100)/100)*100)/100);
});
});
Basic jsfiddle demo: http://jsfiddle.net/jtbowden/YxJCF/
I believe this is due it taking the first input[name^quantity] and first input[name^unitprice] it runs across. Since both rows have the same names, you have to scope your code to make sure it only pulls from its own row and not from others. Does that make sense?

Jquery Disabling individual buttons within search results that all have the same classes applied

If you take a look at: http://www.thebullionstore.co.uk/_shop/?_cat=9
You will see a list of products each wrapped in a div with the class product_box. Inside product_box there several other divs and a form with an add to cart button. inside the form there is a hidden input field called stock_amount with a value, the value attribute is the amount of each product that is in stock. Iv also added a number base to the stock_amount class name to distinguish each product listing such as stock_amount0, stock_amount1 ans so on.
I want to be able to disable each button for each individual product after a certain amount of clicks. The amount of clicks will be equal to the value of stock_amount so in-effect a user cant add more products to the cart than is available.
Adding to the cart is currently done with Jquery but I don't know jquery well enough to figure out how to loop through each product listing and do what I described above.
Any help would be much appreciated.
$("button.addtocart").click(function(e) {
// fetch <input name='stock_amount'> within the clicked buttons form element
var stock_amount_input = $("input[name='stock_amount']", $(this).parent());
// fetch <input name='_qty'> within the clicked buttons form element
var qty_input = $("input[name='_qty']", $(this).parent());
// maybe you want to do some check here
var new_amount = stock_amount_input.val() - qty_input.val();
// set the new calculated value in the stock_amount input
stock_amount_input.val(new_amount);
// if the new_amount is less than 1 we dissable the clicked button
if(new_amount < 1) {
$(this).attr("disabled", "disabled");
}
});
To loop thorough elements you can use the jQuery.each(). Or write something like this:
var nodes = $("form");
for(var i=0; i<nodes.length; i++) {
var node = nodes[i];
// do something
}
But I don't think you need to do this. You can preform the check and the disabling of the button in the click-event-handler. Furthermore you shouldn't forget to check if the entered amount (e.g. 1000) doesn't exceed the stock amount.

Categories

Resources