You are viewing limited content. For full access, please sign in.

Question

Question

Performing calculations with JavaScript in Forms using multiple choice values.

asked on June 12, 2014 Show version history

Hey everyone,

 

I'd like to use a value given to a radio button to calculate a total cost based on a number entered in a following field.  Right now I have 4 options for the radio button.  The "values" I've given them are:  115, 145, 175, and 200.

 

There is a number field following the radio button field that I would like to use along with these to do some math.  This math only needs to happen if the "200" button is selected - anything less will just need to produce the "value" from the radio button in the "total" field.  At which point I need to add $1 per every number entered in the number field over 100 (102 would make the cost $202.00).  This number will reach a maximum of $450.00.

 

I would like this calculation to populate the "total" field.

 

I've been using the CSS classes: "fee", "rooms", and "total".

 

Here's a screenshot of the editor that will hopefully make it easier to understand the context:.

0 0

Answer

SELECTED ANSWER
replied on June 13, 2014 Show version history

The following should work, assuming I understand what you're trying to do.

 

$(function() {
    $(".fee").change(feeCalculator);
  	$('.rooms input').blur(feeCalculator);
});

function feeCalculator() {
    var total = 0

    $(".fee input:checked").each(function(){  
        if ($('.fee input:checked').val() == 200)
        {
            total = Number($(this).val()) + (Number($('.rooms input').val() - 100));
        } else {
            total = Number($(this).val());
        }
    });

    $(".total input").val(total);
}

 

0 0

Replies

replied on June 13, 2014

Thanks!  I'm slowly learning JavaScript through Forms, but it's taking some time.

0 0
replied on June 13, 2014

No problem! Forms is a pretty great way to get started with JavaScript. It's a good idea to use a browser with a debugger, so you can see when your code has errors. I use Firefox with firebug; others here use Chrome and its developer tools.

 

Since we're using the jQuery library, it's a great idea to familiarize yourself with jQuery and what it can do.

 

For me, it's helpful to look at code examples to see appropriate selectors that might be useful for things I want to do. I often refer to the code samples on this page when I want to write code that deals with tables, collections, and radio buttons.

 

There's also this page, which you might find useful as a "getting started" guide to JavaScript in Forms.

0 0
You are not allowed to follow up in this post.

Sign in to reply to this post.