Well, .val() on the select element returns the current value, so you
can simplify that:

$('select#myselect').change(function(){
  var itemText = $(this).find('option:selected').text();
  var itemValue = $(this).val();
 $( '#answer' ).text( itemText + ' is number ' + itemValue );
});

or go even simpler with DOM methods (should be cross-browser, not
sure):

$('select#myselect').change(function(){
  var sel = this.options[this.selectedIndex];
 $( '#answer' ).text( sel.text + ' is number ' + sel.value );
});


On May 18, 12:40 am, "cherry.aus...@gmail.com"
<cherry.aus...@gmail.com> wrote:
> Can I just thank you guys!! I've wasted hours trying to fiddle around
> with selectedIndex and stuff; the best I achieved was to get the html
> object returned :(
>
> It wasn't clear from the docs. Confusingly, I did get the option text
> with $( 'select#myselect option:selected' ).text(). But I couldn't get
> the value as well; I needed both.
>
> To clarify for anyone else struggling with it, here's what I did:-
>
> $( 'select#myselect' ).change( function () {
>   var itemValue;
>   var itemText;
>   $( 'select#myselect option:selected' ).each( function () {
>     itemValue = $( this ).val();
>     itemText = $( 'select#myselect option:selected').text();
>   });
>   $( '#answer' ).text( itemText + ' is number ' + itemValue );
>   // do some work with the answer
>
> });
>
> I don't know why you have to name the select option twice, nor why it
> wouldn't work with $( this ) but there you go ...
>
> Thanks :D
> Of course, if any of you geniuses can improve my code, I'm listening!
>
> Cherry

Reply via email to