Mirt Hlaj
Mirt Hlaj

Reputation: 173

Javascript/JQuery ignore stopPropagation for change event

I have a dropdown menu that contains an input field for search and a list of labels with checkboxes. I added the stopPropagation call so it doesn't close everytime a checkbox is clicked but then the change event on the input field stoped working because of it. Actually it works but I have to mouse click on the dropdown for it to activate.

This is my HTML:

<div class="btn-group">
    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"></button>
    <ul class="dropdown-menu scrollable-menu" role="menu">
        <li><input class="form-control input-sm" id="search" type="text" style="height:100%; width:100%" /></li>
        <li><label class="lbl"><input class="checkbox" type="checkbox" value="1">Something</label></li>
        <li><label class="lbl"><input class="checkbox" type="checkbox" value="2">Something else</label></li>
        <li><label class="lbl"><input class="checkbox" type="checkbox" value="2">And so on</label></li>
    </ul>
</div>

and this are the functions I am using:

$('.dropdown-menu').click(function (e) {
    e.stopPropagation();
});

$("#search").change(function () {
    //do stuff
})

Upvotes: 2

Views: 2483

Answers (2)

hallleron
hallleron

Reputation: 1992

Like Roland Ruul mentioned, change only fires when it loses focus. input is one way you can go, as well as keydown for when the user presses the key down with the search input focused or keyup for when the user releases the key with the search input focused. Here are some examples. Hold the key for example to see how keyup works:

$(function(){

  $('#input').on('input', function(){
    console.log("Input event fired!");
  });
  
  $('#keydown').on('keydown', function(){
    console.log("Keydown event fired!");
  });
  
  $('#keyup').on('keyup', function(){
    console.log("Keyup event fired!");
  });


});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="Input event" id="input">
<input type="text" placeholder="Keydown event" id="keydown">
<input type="text" placeholder="Keyup event" id="keyup">

Upvotes: 1

Roland Ruul
Roland Ruul

Reputation: 1242

jQuery change() is triggered when the input loses focus.

Here is link to documentation.

The change event is sent to an element when its value changes. This event is limited to elements, boxes and elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.

Use input instead, so it's triggered every time the input changes.

$('.dropdown-menu').click(function (e) {
    e.stopPropagation();
});

$("#search").on('input', function () {
    // ... do stuff
});

Here is jfiddle.

Upvotes: 1

Related Questions