Jquery select change

40,202

Solution 1

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

Solution 2

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

Solution 3

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.

Solution 4

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).

Share:
40,202
Ste
Author by

Ste

Updated on August 04, 2022

Comments

  • Ste
    Ste almost 2 years
    <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?

  • JohnP
    JohnP about 13 years
    That's a really weird issue. The problem is not with the code, rather with the attribute name. If you change it to prefix1 it works : jsfiddle.net/hKktc/7 I don't know whether it's a bug or something else
  • phil
    phil about 13 years
    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.
  • Praveen Kumar Purushothaman
    Praveen Kumar Purushothaman over 11 years
    prefix might be a keyword! :)