Reputation: 37
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
Upvotes: 2
Views: 3127
Reputation: 23816
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);
Upvotes: 1
Reputation: 5402
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
Upvotes: 4
Reputation: 64526
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
Upvotes: 3
Reputation: 1844
Try to select every input called = "type". You'll have to modify the input
tag in displayVals like this
function displayVals() {
var checkedValues = $('input[name=type]:checked').map(function() {
alert(this.value);
});
Upvotes: 0
Reputation: 743
Try this
function displayVals() {
var names = $('input[type="checkbox"]:checked').map(function() {
return this.value;
}).get();
return names;
}
Upvotes: 0