0

This issue is making me want to smash my computer. I have a form, I want to calculate values from selections on the form. I have two jsfiddles here, I really want to have it so I can make selections, then calculate on click. But I can't even get the form to work on click. So the other fiddle uses on change and keyup functions. There is an issue on that form as well. If you change the first select to "option 2", you'll see the value for that select ends up being "1.379999999996" instead of "1.38". Why is this happening?

Fiddle with click function JS:

$('#submit').click(function(){
    var price=$(this).find("option:selected").attr('data-price');    
    var ink=$('#ink').val();   
    var loc1=$('#loc1').val();
    var res= price*1 + ink*1 + loc1*1 ; 
    $('#bleh').val( res || 0 );
});

Fiddle with change and keyup functions JS:

$('#ink, #loc1, .sel').on('keyup change',function(){
    var price=$('option:selected', this).attr('data-price');
    var ink=$('#ink').val();   
    var loc1=$('#loc1').val();
        var res= price*1 + ink*1 + loc1*1 ; 
    $('#bleh').val( res || 0 );
});
Potatrick
  • 75
  • 2
  • 14

1 Answers1

0

Your selector $(this).find("option:selected") is wrong as this here points to the #submit button, so you need to find out the select element using its id #style

$('#submit').click(function(){
    var price=$('#style').find("option:selected").attr('data-price');    
    var ink=$('#ink').val();   
    var loc1=$('#loc1').val();
    var res= price*1 + ink*1 + loc1*1 ; 
    $('#bleh').val( res || 0 );
});

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Excellent thank you. Now just to find out why the values aren't returning properly from the `data-price` attribute – Potatrick Aug 20 '13 at 04:08
  • @Potatrick how are you saying it is not returning correct values – Arun P Johny Aug 20 '13 at 04:10
  • Choose option 2 on the first select and see what it returns. It's a minute fraction off of the correct value. – Potatrick Aug 20 '13 at 04:30
  • it is a problem with floating point calculation :( ... you can look at [.toFixed()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed) to fix the number of decimal places – Arun P Johny Aug 20 '13 at 04:35
  • @Potatrick also see http://stackoverflow.com/questions/11695618/dealing-with-float-precision-in-javascript – Arun P Johny Aug 20 '13 at 04:36
  • Thanks, I'll look into those, you've been very helpful. I just don't understand why that happens since the function is only addition. I guess nothing can be easy. – Potatrick Aug 20 '13 at 04:52