Search code examples
jqueryselected

jQuery check if option val and selected, do math and alert


I need to do some calculations based off shipping options. For this example I simply just want to alert() the new price. I want to add 6% to the selected charge and alert() it. I cannot really modify the below html but it adds selected if one of the options is selected:

<select name="ShippingSpeedChoice" onchange="this.form.submit();">
<option value="0">PLEASE SELECT</option>
<option value="701">UPS Ground $9.90 </option>
<option value="703">UPS 3Day Select® $30.88 </option>
</select>

So if option value 701 is selected I would want an alert that displays the total of 9.90 * 1.06....10.49. Currently it displays it no matter what is selected. (ie <option value="703" selected>UPS 3Day Select® $30.88 </option> the alert will popup for this and it shouldn't). Any ideas?

$(document).ready(function() {
  if ($("option[value='701']:selected")) {
    $("option[value='701']").each(function () {                                           
        var isthePrice = $(this).text().replace("UPS Ground $", "");
        var parsedShip = parseFloat(isthePrice);
        var doMath = parsedShip * 1.06;
        alert(doMath.toFixed(2) + " "); });
  }                        
});

Solution

  • You are asking if the value is selected at the moment the DOM is ready. You need to bind an event handler to run the script whenever the option is changed.

    $(document).ready(function() {
        $("select").bind("change", function(){
          if ($("option[value='701']:selected", this)) {
            $("option[value='701']").each(function () {                                           
                var isthePrice = $(this).text().replace("UPS Ground $", "");
                var parsedShip = parseFloat(isthePrice);
                var doMath = parsedShip * 1.06;
                alert(doMath.toFixed(2) + " "); });
          }
        });                     
    });
    

    Is your starting point, although you may well need to be more specific with the option used in the average case.