views:

348

answers:

1

I have a select box that gives a description of a product along with a price. Depending on what the user selects, I'd like to automatically grab that dollar amount from the option selected and assign it to a price input field. My HTML:

<tr>
    <td>
        <select class="selector">
            <option value="Item One $500">Item One $500</option>
            <option value="Item Two $400">Item Two $400</option>
        </select>
    </td>
    <td>
        <input type="text" class="price"></input>
    </td>
</tr>

So based on what is selected, I want either 500 or 400 assigned to the .class input. I tried this but I'm not quite sure where I'm going wrong:

$('.selector').blur(function(){
    var selectVal = ('.selector > option.val()');
    var parsedPrice = parseFloat(selectVal.val());
    $('.price').val(parsedPrice);
});
+3  A: 

First remove everything from the value attribute that is not part of the value.

<tr>
    <td>
        <select class="selector">
            <option value="500">Item One $500</option>
            <option value="400">Item Two $400</option>
        </select>
    </td>
    <td>
        <input type="text" class="price"></input>
    </td>
</tr>

Second change your jQuery to this.

$('.selector').blur(function(){
    var parsedPrice = parseFloat($(this).val());
    $('.price').val(parsedPrice);
});
ChaosPandion
For some reason, the blur functionality isn't working as expected. I would expect to see the value show up automatically in the price field after making a selection, but instead, I have have to actually click into the price field and then click back into the selection and then again click back into the price field and only then does the value show up.
@user306472 - That is actually the way it is supposed to work. Use the `change` event instead.
ChaosPandion