Search code examples
javascriptjqueryoopfunc

How to get div id and set it to anoher func


Have a func that get clicked div id need to give next func this id instead "#dropdown1"

    $(function() {



   $('.drop-down-input').click(function() {

        $elementid = this.id;
        $elementid= "#" + elementid;
     });
      console.log($elementid);
     $("#dropdown1").click(function() {

        $("#dropdown1 .dropdown-list").show();

     }); 

  $("#dropdown1 .dropdown-list li").on('click', function(e) {
    e.stopPropagation();
    $("#dropdown1 .dropdown-list").hide().siblings().val($(this).html());
  });
});

HTML:

<div id="dropdown1" class="styled-input-container drop-down-input">
                   <input id="simple_2" class="drop-down-select" placeholder="input text" type="text">
                   <ul class="dropdown-list">
                       <li>eeee</li>
                       <li>xxxx</li>
                       <li>xxxx</li>
                       <li>xsssxxx</li>
                   </ul>
               </div>

Idea is that I can use this code again in another place. for examle use 2 dropdowns with different ID


Solution

  • Don't send the ID, add a class to the element.

    $('.drop-down-input').click(function() {
        $('.drop-down-input.selected').removeClass('selected'); // Forget the previous selection
        $(this).addClass('selected');
        $(this).find(".dropdown-list").show();
    });
    

    Then in the next function you can use a selector to find the clicked element:

    $(document).on("click", ".drop-down-input.selected li"), function(e) {
        e.stopPropagation();
        $('.drop-down-input.selected .dropdown-list').hide().siblings().val($(this).html());
    });
    

    A benefit of this method over saving the ID in a variable is that you can use CSS to add a style to the selected element.

    Full code:

    $('.drop-down-input').click(function() {
      $('.drop-down-input.selected').removeClass('selected'); // Forget the previous selection
      $(this).addClass('selected');
      $(this).find(".dropdown-list").show();
    });
    
    $(document).on("click", ".drop-down-input.selected li",
      function(e) {
        e.stopPropagation();
        $('.drop-down-input.selected .dropdown-list').hide().siblings().val($(this).html());
      });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="dropdown1" class="styled-input-container drop-down-input">
      <input id="simple_2" class="drop-down-select" placeholder="input text" type="text">
      <ul class="dropdown-list">
        <li>eeee</li>
        <li>xxxx</li>
        <li>xxxx</li>
        <li>xsssxxx</li>
      </ul>
    </div>