Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a "reusable" function in jquery?

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');
like image 322
I_miss_Steve_already Avatar asked Nov 24 '11 01:11

I_miss_Steve_already


1 Answers

$.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.

like image 98
Chris Fulstow Avatar answered Sep 18 '22 14:09

Chris Fulstow