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!
Call it like this:
$('#source').keyup(function() {
doStuff(this, '#destinationTitle', 'SampleTitle');
});
It's just a string :)
If the element is in relation to the other though, you can make it generic, for example if #destinationTitle
is always in the next div, next table cell, etc...always in the same relative place, you can make this cleaner for all keybinds, if you post some sample markup I'll show you how.
Get rid of the double quotes.
精彩评论