Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Get user selected value from select list when using default select=y

Hi I have a Select list liek so:

<select id=cardtype name=cardtype>
<option selected='y' value="debit-0.00-50.00">Debit1</option>
<option value="debit-0.00-50.00">Debit2</option>
<option value="debit-0.00-50.00">Debit3</option>
<option value="Credit-1.00-50.00">CreditCard</option>
</select>

i have been trying a various methods in JQuery to get the value of the user selected value: var card = $('#cardType').val(); var card = $('#cardType :selected').val(); etc etc

However they all just return the value of the default selected option:

 <option selected='y' value="debit-0.00-50.00">Debit1</option>

Does anyone know of a way to get the selected option value that the user selects rather than the default selected value?

EDIT to clarify the JQuery is run when a user hits a link like so:

<label for="paymentAmount">Amount (minimum payment <a class="minPay" href="">£<span id="dueFrom">50.00</span></a>) <span class="instructions"><span class="mandatory">*</span></span></label>

with the following jquery:

$("a.minPay").click(function(event) {
            event.preventDefault();
            $("#paymentAmount").val($("#dueFrom").html());
            var from = parseFloat($("#paymentAmount").val());
            var card = $('#cardType').val();
    });

This does not run when the user select an option in the select list.. and i want the value option not the text :)

like image 276
Arazmus Avatar asked Dec 07 '10 16:12

Arazmus


1 Answers

Make sure you're getting it with the proper id and at the right time, this is the correct method:

$('#cardtype').val();

Note that the id is cardtype, not cardType, it is case sensitive. Also, you need to make sure you're running after that after the user has selected a value, for example:

$('#cardtype').change(function() {
  alert($(this).val());
});

You can test it out here. Also note that your attributes should always be quoted.

like image 158
Nick Craver Avatar answered Oct 13 '22 00:10

Nick Craver