Reputation: 47595
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()?
Upvotes: 1
Views: 664
Reputation: 75650
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());
});
});
Upvotes: 1
Reputation: 5251
If inside doit()
you need the values of A and B, both methods are the same. I would leave your code as it is.
Upvotes: 1
Reputation: 9760
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()));
});
});
Upvotes: 1
Reputation: 60413
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'));
Upvotes: 1