Jquery passing an HTML element into a function
Posted
by christian
on Stack Overflow
See other posts from Stack Overflow
or by christian
Published on 2010-03-15T20:37:31Z
Indexed on
2010/03/15
20:39 UTC
Read the original article
Hit count: 204
jQuery
I have an HTML form where I am going to copy values from a series of input fields to some spans/headings as the user populates the input fields. I am able to get this working using the following code:
$('#source').keyup(function(){
if($("#source").val().length == 0){
$("#destinationTitle").text('Sample Title');
}else{
$("#destinationTitle").text($("#source").val());
}
});
In the above scenario the html is something like:
Sample TitleBasically, as the users fills out the source box, the text of the is changed to the value of the source input. If nothing is input in, or the user deletes the values typed into the box some default text is placed in the instead. Pretty straightforward. However, since I need to make this work for many different fields, it makes sense to turn this into a generic function and then bind that function to each 's onkeyup() event. But I am having some trouble with this. My implementation:
function doStuff(source,target,defaultValue) {
if($(source).val().length == 0){
$(target).text(defaultValue);
}else{
$(target).text($(source).val());
}
}
which is called as follows:
$('#source').keyup(function() {
doStuff(this, '"#destinationTitle"', 'SampleTitle');
});
What I can't figure out is how to pass the second parameter, the name of the destination html element into the function. I have no problem passing in the element I'm binding to via "this", but can't figure out the destination element syntax.
Any help would be appreciated - many thanks!
© Stack Overflow or respective owner