0

I wanted to get the value of chkArray variable when called outside the method.

When I called getValues().total from outside the method I am getting a error message as cannot read property total of undefined.

function getValues(){
chkArray = new Array() ;
$("input[type=checkbox]:checked").each(function fire() {
 var total = chkArray.push($(this).val());
console.log(chkArray)    
});
};

Kindly, help how to call that variable outside the method

2
  • Im confused as to where .total comes in.. total isn't defined anywhere. Commented Oct 15, 2014 at 19:29
  • I have edited please check again Commented Oct 15, 2014 at 19:29

2 Answers 2

1

Use this:

  function getValues(){
     var total = new Array() ;
     $("input[type=checkbox]:checked").each(function fire() {
       total.push($(this).val());
      });
   return total;
  };

Call function

var total= getValues();
console.log(total);
Sign up to request clarification or add additional context in comments.

3 Comments

I am getting an empty array. I wanted to get the value of total that is present inside the fire()
You're getting empty array because you checked no checkboxes, didn't you? And what does fire() do? .each(function () { would do the same job.
@StanimirStoyanov I gave console.log(total) inside the fire() it returning array with elements but the returned total gives empty array even if the checkboxes arechecked
0

function getValues() {
  var total = new Array();
  $("input[type=checkbox]:checked").each(function() {
    total.push($(this).val());
  });
  return total;
};

function doSomething() {
  var k = getValues();
  console.log(k);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
1
<input type="checkbox" name="myCheckbox" value="1" />
<br />2
<input type="checkbox" name="myCheckbox" value="2" />
<br />3
<input type="checkbox" name="myCheckbox" value="3" />
<br />4
<input type="checkbox" name="myCheckbox" value="4" />
<br />5
<input type="checkbox" name="myCheckbox" value="5" />
<br />
<input type="button" onClick="doSomething()" value="Click me" />

2 Comments

Thank you very much for your example. I am able to print ["1", "2", "3"] in console.log(total). but after checking the text boxes when I write the code var k = getValues(); and print console.log(k), I am getting an empty array ([]) I need the values in k after checking in the text boxes
I have just updated my answer. Just make sure you have selected checkboxes - the only scenario I can imagine where you'll get an empty array is when no checkboxes are checked.

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.