Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split text from select dropdown to use for multiplication using Jquery/Javascript

I have a select dropdown to choose a product size which also tells you the price for each sizing.

I want to display the total cost as well has how many hectares it will cover. 1kg = 1hectare

The value is the ID for the sizes and is used when adding to the cart.

<select class="productChoice">
    <option value="">-- Please select --</option>
    <option value="2317474">1KG $180</option>
    <option value="2317475">5KG $100</option>
    <option value="2317476">10KG $200</option>
    <option value="2317477">50KG $900</option>
</select>

<input type="text" id="Units_5183442" class="productTextInput" value="0">

<label id="hectares_5183442"></label> Hectares
<label id="total_5183442"></label>

So you choose your product size, then how many of that size you want to purchase. From there I want to display the two different values in the respective labels.

I'm struggling separating the option text to do what I need. Can't get past the NaN.

What I've got so far is:

$('#Units_5183442').keyup(multiply);
$('select.productChoice').change(multiply);
function multiply() {
    var quantity = parseFloat($('#Units_5183442').val());
    var dollars = cantfigureouthowtodothis
    var size = cantfigureouthowtodothis

    $('#total_5183442').text('$'+(quantity * dollars )); 
    $('#hectares_5183442').text((quantity * size)); 
}
like image 891
Justin Avatar asked Nov 26 '25 08:11

Justin


1 Answers

This will update the hectares and total cost labels:

$(function() {
    $('.productChoice').change(function() {

        if($('#Units_5183442').val() == 0)  // min 1
            $('#Units_5183442').val(1);

        var selectedText = $(this).find('option:selected').text(); 
        var match = selectedText.match(/\d{1,3}KG/g);
        if(match.length == 1)
        {
            var kg = parseInt(match[0].replace('KG',''));
            var costMatch = selectedText.match(/\$\d{1,3}/g);
            if(costMatch.length == 1)
            {
               var cost = parseInt(costMatch[0].replace('$',''));
               var quantity = parseInt($('#Units_5183442').val());  // presume you can only order integer quantities?

               $('#hectares_5183442').text(kg * quantity);
                $('#total_5183442').text('Total cost: $' + cost * quantity)
            }
        }
    });

    $('#Units_5183442').keyup(function() {
        $('.productChoice').trigger('change');
    });
});

JS Fiddle here: http://jsfiddle.net/zud2Z/2/

like image 137
Nathan Avatar answered Nov 27 '25 20:11

Nathan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!