Daniel Viglione
Daniel Viglione

Reputation: 9407

val() on checkbox returns an element not the string literal

I want to get the values of all checked checkboxes. I just want the string literal value.

I try the following:

$('input:checked').map(function() { return $(this).val(); })

The returned data is:

e.fn.init[1]0: "Documents" context: document length: 1 prevObject: e.fn.init[1] __proto__: Object[0]

I do not want that. I just want the string "Documents", which is the value of the selected checkbox in my example.

What am I doing wrong?

Upvotes: 0

Views: 97

Answers (1)

Paul Fitzgerald
Paul Fitzgerald

Reputation: 12129

You need to use get() to turn the jQuery object into an array

 $('input:checked').map(function() { return $(this).val(); }).get();

See full example below.

var res = $('input:checked').map(function() {
    return $(this).val();
}).get();

console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input checked type="checkbox" id="cbox1" value="first">
<input checked type="checkbox" id="cbox2" value="second">

Upvotes: 3

Related Questions