2

I have the following code :

<form>
<input type="checkbox" name="type" value="Club" onclick="getselectedcheckbox()"checked/>Club<br/>
<input type="checkbox" name="type" value="Pub" onclick="getselectedcheckbox()" checked/>Pub<br/>
<input type="checkbox" name="type" value="Home" onclick="getselectedcheckbox()"/>Home<br/>
<input type="checkbox" name="type" value="Concert" onclick="getselectedcheckbox"/>Concert<br/>

<script>
function displayVals() {
var checkedValues = $('input:checkbox:checked').map(function() {
    alert(this.value);
});
   }

$( "select" ).change( displayVals );
displayVals();
</script>

I am trying to get all the checkbox checked, to then send it with ajax. But right now, I have 1 different alert for each checkboxes, is there a way to get all the checked values in one string ?

I've heard of .join(), but I don't really know where to put it in my code. Still beginning with Javascript / jquery :/

Any ideas ?

Thanks, Loneept

Loneept
  • 37
  • 2
  • 8

5 Answers5

4

Declare a array and push all the values into it, example:

   var selected = [];
   function displayVals() {
      var checkedValues = $('input:checkbox:checked').each(function() {
         selected.push(this.value);
      });
   }

 var stringArray =  selected.join();

use array join to convert array to string

StateLess
  • 5,344
  • 3
  • 20
  • 29
3

Is there a way to get all the checked values in one string ?

In your map, return the checkbox value, then use get() which retrieves the JavaScript array of values from the jQuery object. Finally, use join() to convert to a comma separated string.

var checkedValues = $('input:checkbox:checked').map(function() {
    return this.value;
}).get().join(',');

The result would be (with all checked):

Club,Pub,Home,Concert
MrCode
  • 63,975
  • 10
  • 90
  • 112
  • 1
    This answering question as asked but as OP wants to send it using ajax, this seems better to serialize the FORM imho – A. Wolff Mar 17 '15 at 12:19
  • 1
    Thanks, this works perfectly. I'll look into the serialize later, when i'll want to optimize the code :) – Loneept Mar 17 '15 at 12:51
1

Give a form id like myform and simply use:

$('#myform').serialize();

Note: It will not give unchecked checkboxes values

If you want to get unchecked values also then you need to explicitly set unchecked checkboxe's value false before serialize.

$('#myform').find(':checkbox:not(:checked)').attr('value', false);
Manwal
  • 23,450
  • 12
  • 63
  • 93
0

Try this

function displayVals() {
    var names = $('input[type="checkbox"]:checked').map(function() {
      return this.value;
    }).get();

     return names;
}
Ruprit
  • 733
  • 1
  • 6
  • 23
0

Try to select every input called = "type". You'll have to modify the inputtag in displayVals like this

function displayVals() {
var checkedValues = $('input[name=type]:checked').map(function() {
alert(this.value);
});
riciloma
  • 1,456
  • 2
  • 16
  • 31