What i have is working, so I'm just asking if there's a more elegant way to do this. I have:
<form method="post" action="15Action.cfm">
<p><input id="A" name="A1"></p>
<p><input id="B" name="B1"></p>
<p><input id="C" name="C1"></p>
<input name="Submit" type="submit" value="submit">
</form>
If the changes either A or B, then concatenate the two fields together and place them into C. What I have is:
function doit(A,B) {
return A+B;
};
$(function() {
var A = $('#A');
var B = $('#B');
$('#A, #B').change(function() {
$('#C').val(doit(A.val(),B.val()));
});
});
I wonder if I should write
$('#C').val(doit(A,B))
instead, or is it acceptable to pass A.val(), B.val()?
-
2It looks like you edited your original code to reflect the changes suggested by Kyle. I think it would be more helpful to others who come across this question if you had left your original code as it was. Otherwise Kyle's answer doesn't make a lot of sense.jessegavin– jessegavin2010年01月26日 17:25:24 +00:00Commented Jan 26, 2010 at 17:25
4 Answers 4
I wonder if I should write
$('#C').val(doit(A,B))instead, or is it acceptable to pass A.val(), B.val()?
Passing A,B wouldn't work. Your solution looks reasonably elegant, you even cache the jQuery objects to get A,B in the closures you use.
you could make it a little more concise by doing:
function doit(A,B) {
return A+B;
};
$(function() {
var A = $('#A');
var B = $('#B');
$('#A, #B').change(function() {
$('#C').val(doit(A.val(),B.val()));
});
});
1 Comment
Either way is fine really... What it depends on is what kind of params you expect to always be passed to doit. If you paln on olny doingit with jQuery objects (read elements) then i might jsut passin in selectors to doit and do all my lookups in there - or you could pass the jQuery objects themselves as this wouldnt make much of a difference.
function doit(a,b){
return $(a).val()+$(b).val();
}
// these are then functionally equiv.
doit('#A','#B');
doit($('#A'), $('#B'));
Comments
If inside doit() you need the values of A and B, both methods are the same. I would leave your code as it is.
Comments
If all you're doing is concatenating the two values, I would not even bother with a doit() function and just glue the two values together.
$(function() {
$('#A, #B').change(function() {
$('#C').val($('#A').val() + $('#B').val());
});
});