1

This is probably simple, just missing how I should return this data.

var sumInputs = function (input) {
  var reloadData = function () {  
    var sum = 0;
    $(input).each(function() {
        sum += Number($(this).val());
    }); 
    return sum;
  };

  $(window).ready(function () {                  
    var changeOn = $(input);
    changeOn.on('change', function () {
      var data = reloadData();
    });
    changeOn.trigger('change');
  });
};

var sum = sumInputs('.feature');
console.log(sum);

Right now I'm just getting undefined as my result. Here's my jsfiddle: http://jsfiddle.net/bk97qc4L/

Thanks for the help.

0

2 Answers 2

1

Your sumInputs is a function that takes in one parameter and returns nothing. Hence sum evaluates to undefined.

Inside sumInputs, you have declared a variable reloadData (as a function), and made one event binding to run whenever the window is ready. You did not specify any return value, and have not even executed the function reloadData.

I suspect this is what you want: http://jsfiddle.net/bk97qc4L/1/

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I knew it was obvious. I've been working in PHP so much my brain was not computing the answer this morning.
0

$(document).ready(function () {                  
   function sumInputs(input, output) {
      var $input = $(input);
      
      function reloadData() {  
        var sum = 0;
        $(input).each(function() {
            sum += Number($(this).val());
        }); 
        return sum;
      };
    
      $input.on('change', function () {
          $('#output').val(reloadData());
        });
   };
    
    sumInputs('input.feature','#output');
    $('input.feature').change(); // for first time output
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr><td><input type="text" class="feature" value="10" /></td></tr>
    <tr><td><input type="text" class="feature" value="10" /></td></tr>
    <tr><td><input type="text" class="feature" value="10" /></td></tr>
    <tr><td><input type="text" class="feature" value="10" /></td></tr>
</table>

<label for="output">Output:</label>
<input type="text" id="output" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.