Arafat Rahman
Arafat Rahman

Reputation: 1015

Call jQuery function on any change in input field

I have a search field. I want to call my jQuery function in every or any change in that search input field. But while I change in that input field and click outside of the field than the jQuery function called.

html

<input type="search" id="campiagn_search_id" name="campaign_search" placeholder="Campaign Search">

jQuery

   $(document).ready(function(){
      $(document).on('change', '#campiagn_search_id', function() {
        alert("The text has been changed.");
      });
    });

While I type a and click outside of the field than the alert shown. But I want while type a automatically called the jQuery function and show the alert box.

Where is the problem ? Somebody help please ?

Upvotes: 0

Views: 4165

Answers (3)

Manas Pradhan
Manas Pradhan

Reputation: 19

You can use this.

$("#campiagn_search_id").keyup(function(){alert($(this).val());});

Upvotes: 0

Hien Nguyen
Hien Nguyen

Reputation: 18973

With the search function, I suggest you use blur event when user tab or click outside control.

With keyup event your API may be called many times.

$(document).ready(function(){
    $('#campiagn_search_id').blur(function() {
        alert($(this).val());
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="search" id="campiagn_search_id" name="campaign_search" placeholder="Campaign Search">

Upvotes: 0

random
random

Reputation: 7899

Because you have attached change event to input, which gets fired When the element loses focus after its value was changed - https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event.

$(document).ready(function(){
    $('#campiagn_search_id').on('keyup', function() {
        console.log($(this).val());
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="search" id="campiagn_search_id" name="campaign_search" placeholder="Campaign Search">

Upvotes: 3

Related Questions