user2969426
user2969426

Reputation: 127

onchange event in jQuery

I am trying to implement onchange event in jQuery on select field,as jQuery does not create cross browsers compatibility problems. My scripting code is:

<script>
  $('#payment_method').change(function () {
     if ($('#payment_method').val() == 'check') {
        alert('hello');
     }  
  });
</script>

and here is the code for the select field:

<select id="payment_method" name="country" class="form-control" >
    <option value="">Select One</option>
    <option value="check">Check</option>
    <option value="bank_transfer">Bank/Wire Transfer</option>
    <option value="paypal">Paypal</option>
    <option value="smart_card">Smart Money Card</option>
</select>

but nothing is happening when I select check option.

Upvotes: 0

Views: 126

Answers (2)

tilda
tilda

Reputation: 672

You need ready event to run your code when document is ready.

<script>
    $(document).ready(function(){
      $('#payment_method').change(function () {
       if ($(this).val() == 'check') {
       alert('hello');
      } 
    });
      });
    </script>

Upvotes: 2

dinkydani
dinkydani

Reputation: 151

It may be useful to use

$(this).val()

instead of

$('#payment_method').val()

to avoid DOM lookups.

Upvotes: 0

Related Questions