Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Selected value from <ul> by Id in jquery or javascript

I have a ul which is <ul> list, I would like to get the selected value in different function and the list looks like below

<ul class="dropdown-menu" role="menu" id="ChooseAreaList">
   <li><a href="#">Select Destination</a></li>
   <li><a href="#">HSR</a></li>
   <li><a href="#">Bommanahalli</a></li>
   <li><a href="#">Kormangala</a></li>
</ul>

by applying some CSS,JS I am able to get selected value of list like this...

$(".dropdown-menu li a").click(function(){
   var selText = $(this).text();///User selected value...****
   $(this).parents('.btn-group').find('.dropdown-toggle').html(selText+' <span class="caret"></span>');
});

but if i am trying to get this selected value in different function its not working...like this

function BusinessLogic(){
   var selText = $('.dropdown-menu li a').text();
   alert("Its displaying Entire List"+selText);
}

How to do I get selected value of that list in different function?

like image 355
goodyzain Avatar asked Mar 18 '23 23:03

goodyzain


1 Answers

You can put class="selectedLi" in a to indicate the last selected value from dropdown and use same as jquery selector in your BusinessLogic function :

$(".dropdown-menu li a").click(function(){
      // remove previously added selectedLi
      $('.selectedLi').removeClass('selectedLi');
      // add class `selectedLi`
      $(this).addClass('selectedLi');
      var selText = $(this).text();///User selected value...****
      $(this).parents('.btn-group').find('.dropdown-toggle').html(selText+
      ' <span class="caret"></span>');
});

And in below function use selectedLi in jquery selector :

function BusinessLogic()
{
 var selText = $('.dropdown-menu li a.selectedLi').text();

alert("Its displaying Entire List");

} 
like image 90
Bhushan Kawadkar Avatar answered Mar 31 '23 19:03

Bhushan Kawadkar