0

I'm using multiple Bootstrap dropdown controls and need to set a value to an input field when a list item of a specific dropdown is selected. For example, say I have 3 dropdowns:

  • ulSaukContact
  • ulMoselContact
  • ulShipContact

All three are running on the server, and I need to get the value of each so I can save them somewhere. So I figured I should probably save the value of each to a hidden input field that I can reference later. Here is my attempted JS code for doing this:

$("#ulSaukContact li a").on("click", function () {
    alert('sauk'); // <--- Alert is not shown
    var elem = document.getElementById("inpSaukValue");
    elem.Value = $(this).text();
});

and the accompanying markup

        <div class="dropdown">
            <button type="button" class="btn btn-default dropdown-toggle" id="btnSaukList" data-toggle="dropdown" runat="server"
                style="width: 100%;">
                <span style="padding-right: 250px;">Select a Saukville contact</span>
                <span class="caret"></span>
            </button>
            <ul id="ulSaukContact" class="dropdown-menu" role="menu" aria-labelledby="dropdownMenu1" runat="server" style="width: 100%">
                <!--NOTE: Intentionally left blank; li's are generated by code behind to populate users from Sharepoint.-->
            </ul>
            <input id="inpSaukValue" type="hidden" />
        </div>

When I run the app and select a value in the Saukville dropdown, no alert is displayed. Note that the li's and a's within the ul is created on Form_Load so they can be populated with data. I think my selector is wrong. I cleared out my cached files in Chrome (which caused issues before) and I still do not see the alert.

Any advice appreciated (thanks for all the recent JS/BS/JQ advice)...

Paul
  • 1,375
  • 2
  • 21
  • 55
  • If the HTML is added after runtime, do: `$("#ulSaukContact").on("click", "li a", function () {` – tymeJV Oct 06 '14 at 13:26

1 Answers1

1

Because the elements don't exist at the time you're attempting to bind events to them, you need to delegate events to the containing element with on:

$("#ulSaukContact").on("click", "li a", function () {
  ...
user229044
  • 232,980
  • 40
  • 330
  • 338