14
<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?

Nickolay
  • 31,095
  • 13
  • 107
  • 185
Ste
  • 1,497
  • 8
  • 33
  • 63

5 Answers5

10

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

JohnP
  • 49,507
  • 13
  • 108
  • 140
4

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.

James Wiseman
  • 29,946
  • 17
  • 95
  • 158
4

The 2nd alert will return null, because <select> has no attribute prefix.

DanielB
  • 19,910
  • 2
  • 44
  • 50
1

What is it you are expecting exactly?

I find that the second alert - alert( $(this).attr('prefix') ); is the one causing a problem. As is, you get an alert of the prefix number, then an alert of null (caused by the second alert).

phil
  • 174
  • 15
  • Following the tip off by @JohnP above - it does indeed work perfectly if you change the atrtibute `prefix` to something else. I presume `prefix` is reserved. Also, this is a bit more pretty - `$(document).ready(function() { $('#Nazione').change(function(){ alert ( $('option:selected', this).attr('prefix1') ); }); });` That code by @SLaks in [this thread](http://stackoverflow.com/questions/2230704/jquery-getting-custom-attribute-from-selected-option). – phil May 11 '11 at 09:57
0

You probably wanted .val() not .attr('prefix'), to obtain selected value of <select>.

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

        alert( $(this).find("option:selected").attr('prefix') );
        alert( $(this).val('prefix') );
    });
  });
vitas
  • 598
  • 5
  • 9