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

Help with jQuery - Calling functions named from values of select menu

https://w.trhou.se/umtecn7qj3

Hello this is basic stuff I'm sure but I'm kinda lost

This site displays a football team with different options (positions number of games etc) selected from a select menu these are organised in different functions addListDefenders, addListGames etc

When the select menu is changed I want to call the function = to the value name and then with onclick of the go button display the selection

At the moment I've got an alert displaying the value onChange of the select menu but don't know how to call that function

Thanks !

Tom

2 Answers

One way to achieve this.

//when you click on your go button

$('#go').click(function(e){
  e.preventDefault(); // you should remove as well the submit type on the button element.

  var strFun = $('#select').val();
  var strParam; // in case you need to pass some params

  var fn = window[strFun];

  fn(strParam);

});

Thanks for your answer. I couldn't get this to work but It made me rethink the way I called the functions

  • I put the changed the various functions to conditionals inside one function and passed the select.val to the function as a parameter I imagine there'e a better way to do this? But I've got the site to work the way I wanted it to.

https://w.trhou.se/4d21x7dsna