How to create a reusable function in jquery?

I have this code that works fine:

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

I want to be able to reuse it for all other selection fields that I have on my site. So I decided to use the options for this. However, I still could not get the syntax correctly. Here is what I have, but it won’t work. Any help would be appreciated.

 function displayVals(inputfld, boundfld) { var nvenval = $(inputfld).val(); $(boundfld).val(nvenval); } $("select").change(displayVals()); displayVals('#bphonesel', '#bphone'); 
+4
source share
3 answers
 $.fn.displayVals = function(inputfld, boundfld) { this.change(function() { var nvenval = $(inputfld).val(); $(boundfld).val(nvenval); } } $("select").displayVals(); 

Learn more about jQuery docs for creating plugins .

+7
source

Similarly, if you want to make it a jQuery function:

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

Inside the $(this) function, it works just as you expected. Just define it outside of docReady and you are all set up. Having said that, it seems you just need to define the selectors in the displayVals () call inside the .change event:

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

Other than that, I will need to see the rest of your code to understand what might cause the problem.

+4
source

I could do something like:

  (function( $ ){ $.fn.displayVals = function() { this.change(function() { var val = $(this).val(); var elemid = $(this).attr("data-elem"); if (elemid) $("#" + elemid).html(val); }); }; })( jQuery ); $(function () { $(".display-vals").displayVals(); }); 

Then, in any selection item you want to work on, you can do something like:

 <select class="display-vals" data-elem="val-div"> <option>item 1</option> <option>item 2</option> <option>item 3</option> </select> <div id="val-div"></div> 

This uses the html5 attribute "data-". It also means that you don’t need to configure each drop-down menu in the document load event, each of which can specify its own display element in html.

0
source

Source: https://habr.com/ru/post/1382800/


All Articles