javascript - How to use click function with $(this) on children elements with the same class? -


i want create dropdown country->region->city selection. first ul opens click on span , others set show on hover (code @ bottom).

<input type="text" id="srch-area" alt="" class="c-textfield suggestionsinput " name="locationstr" maxlength="" size="" tabindex="3" title="" value="deutschland" defaultvalue="" highlight="y" strict="y" autocomplete="off"> <span class="c-icon-arrow-green-down-left c-icon" id="loc-slctbx"></span> <ul class="dropdown-location-ul" id="dropdown-country" style="display:none;">     <li class="dropdown-location-li">         <strong>deutschland</strong>         <ul class="dropdown-location-ul" style="display:none;">             <li class="dropdown-location-li">                 <strong>brandenburg</strong>                 <ul class="dropdown-location-ul" style="display:none;">                     <li class="dropdown-location-li">                         <strong>oranienburg</strong>                     </li>                     <li class="dropdown-location-li">                         <strong>schwedt</strong>                     </li>                     ...                 </ul>             </li>             <li class="dropdown-location-li">                 <strong>berlin</strong>             </li>             ...         </ul>     </li>     <li class="dropdown-location-li">         <strong>france</strong>     </li>     ... </ul>  $('.dropdown-location-li').hover(function(){     $(this).children('ul').css('left', $(this).parent('ul').width()+'px');     $(this).children('ul').show(); }, function(){     $(this).children('ul').hide(); }); 

this works fine , need make on click change value of near input name of location inside strong tag. tried code below appears $(this) selecting element , parents, need location 1 clicked. please tell me how correctly? maybe have wrong approach , need make id's , stuff, wanted minimise amout of repeating js.

$('.dropdown-location-li').click(function(){     $('#srch-area').val($(this).children('strong').text());     $('#dropdown-country').hide(); }); 

this how shows in console. can see when click on oranienburg selects brandenburg , deutschland parents of element clicked. console screenshot

you have nested .dropdown-location-li elements, click keeps propagating other li elements, firing event handler again etc.
should stop propagation first time

$('.dropdown-location-li').click(function(e){     e.stoppropagation();      $('#srch-area').val($(this).children('strong').text());     $('#dropdown-country').hide(); }); 

Comments

Popular posts from this blog

authentication - Mongodb revoke acccess to connect test database -

r - Update two sets of radiobuttons reactively - shiny -

ios - Realm over CoreData should I use NSFetchedResultController or a Dictionary? -