tags:

views:

58

answers:

4

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()?

+1  A: 

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'));
prodigitalson
+1  A: 

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()));
   });
});
Kyle Butt
Thanks Kyle! I noticed that after I had asked the question, and you are right in pointing that out! I edited the question so that the discussion would stay focused on the passing parameters subject.
cf_PhillipSenn
+1  A: 

If inside doit() you need the values of A and B, both methods are the same. I would leave your code as it is.

alexmeia
+1  A: 

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());
   });
});
jessegavin
Elegant. Perhaps I should ask the question again with a more involved scenario to justify making a function call and passing parameters.
cf_PhillipSenn