this function read the current selected values from a table, I can't get the list of them in a single array readable outside this function.
function getcheckboxed() {
vartoberead = [];
$("input:checkbox[name=test]:checked").each(function(){
vartoberead [vartoberead .length] = $(this).val();
console.log($(this).val(), vartoberead);
return vartoberead;
});
I've declared vartoberead, both inside, than outside the function, tried with:
var myoutsidevar = getcheckboxed();
but always return
[undefined]
Every help is appreciated
6 Answers 6
You can shorten this up a bit:
var values = $("input:checkbox[name=test]:checked").map(function() {
return this.value;
}).get();
Edit: To make this a function and return:
function getcheckboxed() {
return $("input:checkbox[name=test]:checked").map(function() {
return this.value;
}).get();
}
5 Comments
get() do in this instance?.get() creates the basic Array @Curt -- else it'll be a jQuery object.You can use map:
var vartoberead = $("input:checkbox[name=test]:checked").map(function(){
return $(this).val();
});
map() does actually return something, so you don't need to push to an array but instead just let jQuery fill the array for you with the returned values.
Comments
you should return after the each() cycle (and not inside the cycle as you're doing) anyway you could also use serializeArray
function getcheckboxed() {
return $("input:checkbox[name=test]:checked").serializeArray();
};
Comments
When you print the value inside de each ( console.log($(this).val(), vartoberead); ) it show the values correctly ?
Other thing is that you are returning the value inside the each.
Try this:
function getcheckboxed() {
vartoberead = [];
$("input:checkbox[name=test]:checked").each(function(){
vartoberead.push($(this).val());
});
return vartoberead;
}
Comments
I have a pure javascript solution for this . I have used html array i.e all checkboxes having same name (say test[])
function getCheckBoxesValues()
{
var values=[];
for(var i=0;i<document.getElementsByName('test[]').length;i++)
{
if((document.getElementsByName('test[]')[i]).checked)
{
values.push((document.getElementsByName('test[]')[i]).value);
}
}
return values;
}
<input type="checkbox" name="test[]" value="c1"/>
<input type="checkbox" name="test[]" value="c2"/>
<input type="checkbox" name="test[]" value="c3"/>
<input type="checkbox" name="test[]" value="c4"/>
<input type="checkbox" name="test[]" value="c5"/>
<button onClick="alert(getCheckBoxesValues());">Result</button>
Comments
You have to modify you code to valid JavaScript code.
That is:
vartoberead [vartoberead .length] should be vartoberead[vartoberead.length] without any spaces. Beside this issue everything else is ok with your code.
Just by looking at your code I would rather use vartoberead.push($(this).val()) to add to the returned array than looking at the arrays length.
vartoberead.push($(this).val());