Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Casey Ydenberg
Casey Ydenberg
15,622 Points

RESOLVED: Setting the value of a dropdown list with jQuery

Fixed this. I really need to learn when to step away from the keyboard.

I'm having trouble setting a dropdown list to show a particular item using jquery.

Here is my code (currently):

$("#dropdown option").filter(function() {
    if ( $(this).val() == "needle" ) {
        alert( $(this).val() );
        return true;
    }
 }).prop('selected', true);

The correct value shows up in the alert, but the dropdown menu does not change. I don't set any of the options to selected by default (in the raw HTML). If it makes a difference, once of the options is blank, and has an empty string as a value, but I've tried removing that and it makes no difference.

Oh, and I have jQuery 1.9.0 on the site.

I'm not sure what to try, thanks for any help!

Casey

3 Answers

Casey Ydenberg
Casey Ydenberg
15,622 Points

The code which worked was:

$("#dropdown option").prop('selected', false).filter(function() {
    return $(this).text() == 'needle';  
}).prop('selected', true);

Among other problems, I still had the line:

$('dropdown option').val() = 'needle';

which doesn't work, but I had written into the script earlier, and had forgotten to remove or comment out. That's what I meant about stepping away from the keyboard.

Casey

Nick Pettit
STAFF
Nick Pettit
Treehouse Teacher

Hi Casey Ydenberg,

Glad you figured it out!

What was the solution to your problem?

Nick Pettit
STAFF
Nick Pettit
Treehouse Teacher

Awesome, thanks Casey! I just wanted to make sure we got a clear solution in here. Nothing is more annoying than finding a forum post that got resolved without seeing the solution! :)