-2

I know this question has been asked many times, but in different forms. I want to access the selected variable elsewhere within the scope of the topmost function (alert is currently returning undefined). I know I need to use a return in some way or another. Thank you in advance.

$('#people_search_mobile').change(function() {

  var selected;

  $('li a', $('#suggestions')).bind('click.autocomplete',function(){ 
    selected = ($(this).text());
  });

  alert(selected);

}
po.studio
  • 4,007
  • 5
  • 25
  • 37

2 Answers2

4

This doesn't make any sense. The li a hasn't been clicked yet, when the alert happens. The alert will always show undefined, the code to assign a value to selected has not run, and may never run.

If you want to alert the value, you need to do so at the time the li a is actually clicked:

$('#people_search_mobile').change(function() {

  var selected;

  $('li a', $('#suggestions')).bind('click.autocomplete',function(){ 
    selected = ($(this).text());
    alert(selected);
  });


}
user229044
  • 232,980
  • 40
  • 330
  • 338
1

Meagar is correct, however I find that sometimes it helps to write the function elsewhere, that way I am keeping the event handler clean.

$('#people_search_mobile').change(function() {

  var selected, myClickHandler;

  myClickHandler = function(){
    selected = ($(this).text());
    alert(selected);
  };

  $('li a', $('#suggestions')).bind('click.autocomplete', myClickHandler);

}

Edit: Or if you want to pass the selected value to another function elsewhere...

  myClickHandler = function(){
    selected = ($(this).text());
    showMyAlert(selected);
  };

...

function showMyAlert(selected){
  alert(selected);
}
Patrick
  • 555
  • 1
  • 5
  • 13