Jquery select change

Ste picture Ste · May 11, 2011 · Viewed 40.2k times · Source
<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?

Answer

JohnP picture JohnP · May 11, 2011

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