Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery select change

<select id="Nazione" name="Nazione">
    <option prefix='+93' value='AF' >Afghanistan </option>
    <option prefix='+355' value='AL' >Albania </option>
    <option prefix='+213' value='DZ' >Algeria </option>
    <option prefix='+376' value='AD' >Andorra .... etc
</select>

and this js

$(document).ready(function() {  
    $('#Nazione').change(function(){

        alert( $(this).find("option:selected").attr('prefix') );
        alert( $(this).attr('prefix') );
    });
  });

I have alert NULL... WHy?

like image 272
Ste Avatar asked May 11 '11 09:05

Ste


Video Answer


2 Answers

Your code is fine. Here's a demo : http://jsfiddle.net/hKktc/1/

The reason you're not getting a value for the second alert call is because the attribute prefix doesn't exist for the select and only exists for the option

like image 52
JohnP Avatar answered Sep 19 '22 18:09

JohnP


In your code, $(this) refers to the <select>, not the option. The prefix attribute does not exist on the <select>

This will cause the problem with the second example.

like image 29
James Wiseman Avatar answered Sep 21 '22 18:09

James Wiseman