Tuesday, August 7, 2012

jQuery selector nuances

​<select name="Beatle" id="Beatle"​​​​​​​​​​​​​​​​​​​​​​​>
    <option id=9>John</option>
    <option id=8>Paul</option>
    <option id=7 selected>George</option>
    <option id=6>Ringo</option>
</select>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​


<script>
 var selectedText = "";

 selectedText = $('#Beatle').text();
 alert('Not Correct: ' + selectedText);

 selectedText = $('option:selected','#Beatle').text();
 alert('Correct: ' + selectedText);

 selectedText = $('#Beatle:selected').text();
 alert('Not correct: ' + selectedText);

 selectedText = $('#Beatle :selected').text();
  alert('Correct: ' + selectedText);

});
</script>


Live test: http://jsfiddle.net/5XAYh/

No comments:

Post a Comment