1

I want to collect checked checkboxes (values) with a classname and put them into an array. Just like that one:

var a = new Array();
$('.categoriesCb').each(function(i, item) {
  if ($(item).prop('checked'))
  {
    a.push($(item).val());
  }
  alert(JSON.stringify(a));
});

my problem is its a bit big. Cant it be done with one-line?11

2

4 Answers 4

1

You can use .map() function along with .get(). You can also eliminate paramete item and use context this:

var a = $('.categoriesCb:checked').map(function(){
  return $(this).val();
}).get();
Sign up to request clarification or add additional context in comments.

Comments

1

Use jQuery.map()

$('.categoriesCb:checked').map(function() {
  return this.value;
}).get();

Comments

1

another way is to use jQuery.makeArray() with .map():

var arr = jQuery.makeArray($(':checked').map(function(){ return this.value; }));

$('pre').html(JSON.stringify(arr));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" checked name="options" value="1" />
<input type="checkbox" name="options" value="2" />
<input type="checkbox" name="options" value="3" />
<input type="checkbox" checked name="options" value="4" />
<input type="checkbox" checked name="options" value="5" />

<br>
<pre></pre>

Comments

1

Just a pure JS single liner. Note that node list to array conversion with the spread operator works fine in Firefox but with Chrome it's only possible with v51 on. Otherwise you will have to go with the good old Array.prototype.map.call(document.querySelectorAll("input[type=checkbox][checked]"), e => e.value) method.

var arr = [...document.querySelectorAll("input[type=checkbox][checked]")].map(e => e.value);

console.log(JSON.stringify(arr));
<input type="checkbox" checked name="options" value="1" />
<input type="checkbox" name="options" value="2" />
<input type="checkbox" name="options" value="3" />
<input type="checkbox" checked name="options" value="4" />
<input type="checkbox" checked name="options" value="5" />

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.