How can I create a Javascript function to manage (Bootstrap) dropdown menu clicks instead of creating a large number of listeners?

Viewed 69

My project has a large number of dropdown menus. My current scheme is to create jquery listeners for each control, however, it seems reasonable that a single function could accomplish the same task. Please see the onlick event in the markup.

<div class="input-group">
   <div class="input-group-prepend">
      <button id="PrimaryPhoneType" class="btn btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Type</button>
      <div id="ddlPrimaryPhoneType" class="dropdown-menu" onclick="ManageDDlClicks('ddlPrimaryPhoneType','tbPriPhoneType')">
         <a class="dropdown-item" href="#">Cell</a>
         <a class="dropdown-item" href="#">Home</a>
         <a class="dropdown-item" href="#">Work</a>
      </div>
   </div>
   <input type="text" class="form-control" id="tbPriPhoneType" runat="server">
</div>

Current listener scheme:

  $('#<%=ddlPrimaryPhoneType.ClientID %> a').click(function () {
     $('#<%=tbPriPhoneType.ClientID %>').val($(this).html());
  });

Proposed new function:

function ManageDDlClicks(src, tgt) {
   let list = document.getElementById(src).getElementsByTagName('a');
   console.log(list);
   var selItem = list.???
   document.getElementById(tgt).value = selItem
}

Debugging & studying the contents of the "list", I see nothing in the nodes that point to which item was selected.

1 Answers

I'm not 100% sure if I'm understanding you correctly, but I would drop the onClick in the markup, and make an event handler that can handle all clicked events. If your markup remains consistent something like this could work:

$('.dropdown-menu a').click(function () {
  $(this).parents('.input-group-prepend').next().val($(this).text())
});

https://jsfiddle.net/p03btj92/

There are certainly different ways of doing it though:

$('.dropdown-menu a').click(function () {
  $(this).parents('.input-group').find('input[type="text"]').val($(this).text())
});

https://jsfiddle.net/af4ke57b/

Using id based selectors is going to require you to write code specifically for each element you want to interact with. The idea is to instead use the $(this) selector, in conjunction with reusable classes.

From there you can use DOM Traversal Methods to find the element you would like to modify. In this case parents, next, and find were used.

Related