0

I kind of got stuck with this code here. I am trying to retrieve the option text.

HTML code

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>

  $(document).ready(function() { 
     for(i=0; i<list.length; i++) { // assume list[i] contains different names
        var name_options = $('<option>' + list[i] + '</option>');
        $('#names').append(name_options);
     }

 /* I want to retrieve data when a particular option is selected. But this doesnt work*/
 $('#names').click(function(){
  var val = $(this).find(':selected').html();
 });

});

</script>
</head>
<body>
 <select id='names' class='combobox'>
  !-- options for names go here --> 
 </select>
</body>
</html>

I was unable to retrieve the selected value. And hence i used $("#names") as my selector since $("#names option") does not work. What am I doing wrong here?

2 Answers 2

1

You want to use a change() handler and you can get the value directly from the <select> itself.

 $('#names').change(function(){
    var val = $(this).val();
 });

During the selection process you will have several click events which is one reason click() won't be of much help

Sign up to request clarification or add additional context in comments.

Comments

1

Try

$("#names option:selected").text();

or in your code

$(this).find(':selected').text();

2 Comments

A quik question, where is it recommended to use the "$(this).find(':selected').text();" ? After appending or before appending?
After. But as charlietfl pointed out, better use change event rather than click.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.