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');
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');
Share
Improve this question
edited Nov 24, 2011 at 1:18
Ry-♦
225k56 gold badges489 silver badges497 bronze badges
asked Nov 24, 2011 at 1:12
I_miss_Steve_alreadyI_miss_Steve_already
2512 gold badges6 silver badges17 bronze badges
3 Answers
Reset to default 11$.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 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.
I might 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, on any select element that you want this 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 an html5 style "data-" attribute. This also means that you don't have to set up each individual dropdown in the document load event, each select can specify its own display element in html.