Search code examples
javascripthtmlcssmaterialize

Input form from Dropdown called by Button closes when inputing something


I'm currently trying to get a dropdown with a simple input field to work.

I have this piece of code in my html:

<li>
    <a class='dropdown-button btn' data-beloworigin="true" href='#' data-activates='dropdown2'>Teamspeak</a>
    <ul id='dropdown2' class='dropdown-content'>
        <li>
            <input id="username" type="text" class="validate">
        </li>
        <li>
            <a href="ts3server://TEAMSPEAKSERVER/?port=9987">Join</a>
        </li>
    </ul>
</li>

It's working alright so far and looks like I want it to but as soon as I try to input something in the Username field the Dropdown closes. How can I stop it from closing when trying to input something? When I click the button and then press Tab, I can input somethings without problem, which I kind of don't understand.

Also, can anyone maybe give me a tip on how to get the input into the XXX below?

<a href="ts3server://TEAMSPEAKSERVER/?port=9987&nickname=XXX">

Thanks in advance to anyone who can maybe help me.


Solution

  • When you click on input, the event is propagated to parents, which causes the dropdown close. Use the following jQuery code to stop event propagation:

    $(document).ready(function(){
        $("#username").click(function(e){
            e.stopPropagation();
        });
    });
    

    See also: https://api.jquery.com/event.stoppropagation/