Search code examples
javascriptjquerykeyuponkeyup

.on('keyup', function(){ to trigger only on keyup


I want this to trigger only on keyup and not before. Can anyone help please?

$(function() {
$('#acf-field_5a32085c7df98-field_5a3208f87df99').on('keyup', function() {
    $('#link-headline-fb').text($(this).val());
}).keyup();   
});

It is currently displaying empty text before keyup, yet I want this to display the default PHP value unless text is changed. Let me know if you need more.


Solution

  • It is because you are invoking a keyup event after you attach your event listener. Remove .keyup() like so:

    $(function() {
        $('#acf-field_5a32085c7df98-field_5a3208f87df99').on('keyup', function() {
            $('#link-headline-fb').text($(this).val());
        });
    });
    

    $(function() {
      $('#acf-field_5a32085c7df98-field_5a3208f87df99').on('keyup', function() {
        $('#link-headline-fb').text($(this).val());
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="link-headline-fb">
    </div>
    <input id="acf-field_5a32085c7df98-field_5a3208f87df99" />

    Fiddle: https://jsfiddle.net/ryanpcmcquen/dj7yqyec/

    As a side note, I find $(document).ready( to be far clearer than $(function () {. The latter looks too much like an IIFE.