0

I have a HTML doc like this

<div>
     <span>checkbox 1 : </span><input type="checkbox" value="12" />
     <span>checkbox 2 : </span><input type="checkbox" value="23" />
     <span>checkbox 3 : </span><input type="checkbox" value="38" />
     <span>checkbox 4 : </span><input type="checkbox" value="49" />
</div>
<input type="submit" value="Make" onclick="do_it()" />

I want to have an array which contains values of checked checkbox inputs.

for example if checkbox 1 and checkbox 3 are checked I need this array = [12,38].

I have tried several ideas with Javascript and JQuery but I couldn't fix it :(

2
  • 2
    Where are you stuck? Were you not able to select the inputs? If you were, were you not able to filter down to the checked ones? If you were, were you not able to get the values? If you were, were you not able to build an Array? Commented Mar 5, 2013 at 19:27
  • it is always better to paste the code whatever you tried. Commented Mar 5, 2013 at 19:59

2 Answers 2

4
var arr = $('input[type=checkbox]:checked').map(function(){
       return this.value;
}).get();
Sign up to request clarification or add additional context in comments.

Comments

-1

Another alternative, but not as dry as undefineds:

http://jsfiddle.net/KTR9r/1/

<div>
     <span>checkbox 1 : </span><input type="checkbox" value="12" />
     <span>checkbox 2 : </span><input type="checkbox" value="23" />
     <span>checkbox 3 : </span><input type="checkbox" value="38" />
     <span>checkbox 4 : </span><input type="checkbox" value="49" />
</div>
<input id="my_submit" type="submit" value="Make" />

$("#my_submit").click(function() {

    var my_array = [];

    $("input:checkbox" ).each(function() {
        if( $(this).prop('checked') ){
            my_array.push( $(this).val() );
        }
    });    

    console.log(my_array);

});

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.