proggrock
proggrock

Reputation: 3289

jQuery calling keyup event not working

Need a little help...

The following adds a converted currency label after an input for a numeric value - works fine when I press keyup (I can see the coverted label):

  $(document).ready(function(){ 
    $("input.currency-field").each(function () {
        $(this).after("<label class='currency'></label>");           
    });

    $("input.currency-field").bind("keyup", function () {
        $(this).siblings('label.currency').text($(this).val());
        $(this).siblings('label.currency').formatCurrency();
    });
});

I'd like to have the converted values load when the page loads, rather than waiting to press keyup. I've tried to call the keyup event after adding the label in the .each function, but I can't seem to get it to work (also tried calling $("input.currency-field").keyup() outside the function;

Upvotes: 0

Views: 1948

Answers (4)

Joe K
Joe K

Reputation: 104

I've usually found keyup events to be unreliable in various way. I would probably move to a keypress() event to bind to, unless you are specifically looking for keys to be held down and then let go with different functionality for each action.

If you want to have the values calculated when the document is ready, you could take the anonymous function, and make it a "real" named function, then call it when the document is ready as well as attach it to keyup/keypress events.

Upvotes: 1

Matthew Riches
Matthew Riches

Reputation: 2286

It would be best to wrap it all in a function then use this for both the bind and on document ready (or where ever else you want to use it), however you can use trigger for what you are trying to do:

$("input.currency-field").trigger('keyup');

This should trigger the keyup event providing it has been set.

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337550

Put the code into a function and then call that on load, and on the keyup event. Try this:

// Load
$("input.currency-field").each(function () {
    $(this).after("<label class='currency'></label>");  
    setLabelValue($(this));
});

// Keyup
$("input.currency-field").bind("keyup", function() { setLabelValue($(this)) });

function setLabelValue($el) {
    $el.siblings('label.currency').text($el.val());
    $el.siblings('label.currency').formatCurrency();
});

Upvotes: 2

coolguy
coolguy

Reputation: 7954

1.Wrap it in Ready handler

$(document).ready(function(){
      $("input.currency-field").each(function () {
        $(this).after("<label class='currency'></label>");           
    });

    $("input.currency-field").bind("keyup", function () {
        $(this).siblings('label.currency').text($(this).val());
        $(this).siblings('label.currency').formatCurrency();
    });

});

Upvotes: 1

Related Questions