Home > Software engineering >  Add value of selected radio button to user input sum
Add value of selected radio button to user input sum

Time:06-20

I have created a basic calculator that adds 24% to the number that the user types in.

I am trying to add in a second step where the user selects a radio button and this also gets added on to the total of the number generated. I have started writing an on change event, but I'm not sure that this is the best way to do it.

$(document).ready(function() {

  var biddingFee;
  var $lotValue = $("#lotValue"),
    $bid = $("#totalBid"),

    $buyersPremium = $("#buyersPremium"),
    $liveBiddingFee = $("#liveBiddingFee")


  $('input[type=radio][name=group1]').change(function() {
    if (this.value == '0') {
      biddingFee = 0;
    } else if (this.value == '3') {
      biddingFee = 3;
    } else if (this.value == '5') {
      biddingFee = 5;
    } else if (this.value == '6') {
      biddingFee = 6;
    }
  });

  $lotValue.keyup(function(e) {
    if (e.which == 13) {
      return;
    }

    var lotValue = parseFloat($lotValue.val()),
      bid = lotValue * 0.24;

    if (isNaN(bid) || isNaN(lotValue)) {
      $bid.hide();
      return;
    }

    var bidValue = lotValue   bid;

    $('.line').hide();

    $buyersPremium.fadeIn().find(".buyersPremiumNumber").text((bid).toFixed(2));

    $bid.fadeIn().find(".totalBidNumber").text((bidValue).toFixed(2));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<p>1. Enter your bid: <input name="lotValue" id="lotValue" type="number"  /></p>

<p id="buyersPremium">The Buyers Premium (inc VAT) is £<span ></span></p>

<br>

<div >
  <p>2. Choose a live bidding method.</p>
  <label><input type="radio" name="group1" value="0" checked>Type 1 (£0)</label>
  <label><input type="radio" name="group1" value="3">Type 2 (£3)</label>
  <label><input type="radio" name="group1" value="5">Type 3 (£5)</label>
  <label><input type="radio" name="group1" value="6">Type 4 (£6)</label>

  <p id="liveBiddingFee">The Live Bidding Fee is £<span id="price"></span></p>
</div>

<br>

<p id="totalBid">Total £<span ></span></p>

Working jsfiddle: https://jsfiddle.net/devful_rs14/wa7xcns4/2/

CodePudding user response:

To do what you require, the simplest, most accurate, most maintainable and most extensible method is to have a single function which retrieves all the required values from the DOM when any of the DOM elements involved in the calculation is updated. This avoids the need for ugly global variables, and keeps the logic contained in a single place.

In addition to the above, note that you should be using the input event to listen for textbox changes, not keyup, as the former also fires when content is pasted in using the mouse. In addition you can apply a common class attribute to the radio inputs to make selecting them more succinct.

Lastly, note the use of toLocaleString() instead of .toFixed(2) when displaying the currency value. This will avoid rounding errors, and also format the numeric value in to a regional currency string. It will also allow you to easily tailor the UI to the user's region, if necessary. I've just hard-coded it to en-GB for this example though, to follow the example in the question.

With all that said, here's a working example:

jQuery($ => {
  let biddingFee;
  let buyersPremiumFactor = 0.24;
  let locale = 'en-GB'
  let currencyLocaleSettings = { style: 'currency', currency: 'GBP' };

  let $lotValue = $("#lotValue");
  let $buyersPremium = $("#buyersPremium");
  let $bid = $("#totalBid");
  let $biddingMethods = $('.biddingMethod');
  let $liveBiddingFee = $("#liveBiddingFee");
    
  let calculateBidTotal = () => {
    let bidValue = parseFloat($lotValue.val()) || 0; // coerce value to zero if non-numeric
    let buyersPremiumValue = bidValue * buyersPremiumFactor; 
    let biddingMethodValue = parseInt($biddingMethods.filter(':checked').val(), 10);
    let totalBidCost = bidValue   buyersPremiumValue   biddingMethodValue;

    $buyersPremium.fadeIn().find(".buyersPremiumNumber").text(buyersPremiumValue.toLocaleString(locale, currencyLocaleSettings));
    $liveBiddingFee.fadeIn().find("#price").text(biddingMethodValue.toLocaleString(locale, currencyLocaleSettings));
    $bid.fadeIn().find(".totalBidNumber").text(totalBidCost.toLocaleString(locale, currencyLocaleSettings));
  }

  $biddingMethods.on('change', calculateBidTotal)
  $lotValue.on('input', calculateBidTotal);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<p>
  1. Enter your bid: 
  <input name="lotValue" id="lotValue" type="number"  />
</p>
<p id="buyersPremium">
  The Buyers Premium (inc VAT) is <span ></span>
</p>
<br />

<div >
  <p>2. Choose a live bidding method.</p>
  <label><input type="radio"  name="group1" value="0" checked>Type 1 (£0)</label>
  <label><input type="radio"  name="group1" value="3">Type 2 (£3)</label>
  <label><input type="radio"  name="group1" value="5">Type 3 (£5)</label>
  <label><input type="radio"  name="group1" value="6">Type 4 (£6)</label>
  <p id="liveBiddingFee">The Live Bidding Fee is <span id="price"></span></p>
</div>
<br>

<p id="totalBid">
  Total <span ></span>
</p>

  • Related