How to create a "reusable" function in jquery?

18,850

Solution 1

$.fn.displayVals = function(inputfld, boundfld) {
    this.change(function() {
        var nvenval = $(inputfld).val();
        $(boundfld).val(nvenval);
    }
}

$("select").displayVals();

Check out the jQuery docs on authoring plugins for more info.

Solution 2

Like this if you wanted to make it a jQuery function:

$.fn.displayVals = function() {
// Function stuff goes here
});

$('#element').displayVals()

Inside the function, $(this) works just as you'd expect it to. Just define this outside the docReady and you're all set. Having said that, it looks like you just need to define the selectors in the displayVals() call inside of the .change event:

$("select").change(displayVals('#bphonesel','#bphone'));

Other than that, I'd have to see the rest of your code to understand what might be causing a problem.

Share:
18,850
I_miss_Steve_already
Author by

I_miss_Steve_already

Austin Texas is a cool place to be. I'm having the time of my life, learning more every day. Some day, I'm going to grow up. But maybe I'll wait till after I'm dead. @gwhizvideo

Updated on June 16, 2022

Comments

  • I_miss_Steve_already
    I_miss_Steve_already almost 2 years

    I have this bit of code that works great:

    function displayVals() {
        var phonevals = $("#bphonesel").val();
        $('#bphone').val(phonevals);
    }
    
    $("select").change(displayVals);
    displayVals();
    

    I want to be able to reuse it for all the other select boxes I have on my site. So, I thought I'd use parameters to do it. However, I've so far been unable to get the syntax correct. Here's what I've got, but it doesn't work. Any help would be appreciated.

    function displayVals(inputfld, boundfld) {
        var nvenval = $(inputfld).val();
        $(boundfld).val(nvenval);
    }
    
    $("select").change(displayVals());
    displayVals('#bphonesel', '#bphone');
    
  • Ry-
    Ry- over 12 years
    You shouldn't use $(this) inside a jQuery function, this is already an extended object.
  • jblock
    jblock over 12 years
    Whoopsie. You're right :) Chris Fulstow's answer below is much better, anyway.
  • I_miss_Steve_already
    I_miss_Steve_already over 12 years
    Thanks for the input. I got into another part of the project and haven't been able to try these suggestions yet, but I will very soon, and then report back. :<)g