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 jQuery Basics (2014) Creating a Mobile Drop Down Menu Using change()

Using change() in jQuery Basics

hello and happy holidays!

confused by jQuery; here's my question:

How do i modify the $button click code so it performs the redirect when the $select is changed?

if anyone can take a look at the code below and make suggestions, i would appreciate it:

//Create a select and append to #menu
var $select = $("<select></select>");
$("#menu").append($select);

//Cycle over menu links
$("#menu a").each(function(){
  var $anchor = $(this);
  //Create an option
  var $option = $("<option></option>");

  //Deal with selected options depending on current page
  if($anchor.parent().hasClass("selected")) {
    $option.prop("selected", true);
  }
  //option's value is the href
  $option.val($anchor.attr("href"));
  //option's text is the text of link
  $option.text($anchor.text());
  //append option to select
  $select.append($option);
});
//Create button 
var $button = $("<button>Go</button>");
$("#menu").change($button);
//Bind click to button
$button.click(function(){
  //Go to select's location
  window.location = $select.val();
});

2 Answers

I'm pretty sure you are using change() wrong. I've used it with a function instead of a variable.

   $('select').change(function(){
      //redirect code
});

To expand on Joseph's code, if you want to redirect based on the change in the select element, the syntax is

$select.change(function(event_object) {
    window.location = $(this).val();
});

.change() works by choosing the element you want to watch for changes

$('css-selector') 

or

 var $element = $('<element></element>');

and chaining the function at the end. This is how basic jquery works.

You can even add these event handlers before it has been appended to the page.