Lynx
Lynx

Reputation: 1482

use option output rather than option value

I have a simple jquery script set up to calculate the cost of services for a user. the script works great! However, my database side calls to go another route. How can I use the actual output of the option for the calculation rather than the value

jquery:

    var $selections = $('#selections');
var $selects = $("select").change(function () {
    var total = 0;
    $selections.empty();
    $selects.each(function () {
        var $selected = $(this).find("option:selected");
        var price = parseFloat($selected.data("price")) || 0;
        total += price;
        if($selected.val() !== ''){
            $('<li />', {
                text: $selected.val() + $(this).parent().clone().children().remove().end().text()+" " + $selected.data("price")
            }).appendTo($selections)
        }
    })
    $(".summary").text('Est. Total $' + total);
})

HTML with PHP:

<select name="rooms" id="Areas"> 
<option value="" selected="selected">0</option>
 @foreach ($room as $rooms)
 <option data-price="{{ $rooms->pr_clean }}" value='{{ $rooms->room  }}'>{{ $rooms->room  }}</option>
 @endforeach
</select>

Basically I want to be able to add something different in the value field to go into the database but still calculate how many room they are wanting to select using {{ $rooms->room }}

here is a fiddle with the basic idea of how my script works. http://jsfiddle.net/arunpjohny/xf9Fp/

Upvotes: 1

Views: 92

Answers (1)

Sergio
Sergio

Reputation: 28845

In jQuery .val() will give you the option's value when defined inside the <option> tag. If there is no value in the option it will get the text of the option.

<option value="" selected="selected">0</option>
        ^------^                     ^
         value                      text

So because some of your options have value="", jQuery's .val() will get that value, which is a empty string. Without value="" inside the <option> tag .val() would give you 0.

To be sure you always get the text of the option you can use .text().

So use this: if($selected.text() !== ''){

Upvotes: 1

Related Questions