Reputation: 19713
I have many checkboxes in a dynamically produced (ASP) photo gallery. Each checkbox has the name 'photos' and contains a photo ID in the value, like this:
<form name="selectForm" id="selectForm">
<input type="checkbox" onclick="selectPhoto(<%=rs1.Fields("photoID")%>)" id="checkbox_<%=rs1.Fields("photoID")%>" class="photos" name="photos" value="<%=rs1.Fields("photoID")%>">
</form>
Without submitting a form, when the user clicks the checkbox, I need to create a comma (,) separated list of all the checked values for the checkbox named 'photos'. So this is what I tested but it alerts 'undefined'! The ASP is correct, for those not familiar with it.
function selectPhoto(id) {
... other stuff that uses id ...
var allValues = document.selectForm.photos.value;
alert(allValues);
}
But as I said above, this returns 'undefined' and I can work out why. When a user selects a photo, I simply need to display a list of all the photo ID's that have been clicked e.g. 1283,1284,1285,1286...
Any ideas what I am doing wrong here? Or is there another way to achieve this?
Upvotes: 0
Views: 139
Reputation: 10606
I believe that the problem comes from the fact that "document.selectForm.photos
" is not an input but an array. I have some code for you that worked:
<script>
function selectPhoto(id) {
var allCheckbox = document.selectForm.photos;
var allValues = []
for (var i=0; i<allCheckbox.length; i++){
if (allCheckbox[i].checked){
allValues.push(allCheckbox[i].value)
}
}
alert( allValues.join(',') )
}
</script>
<form name="selectForm" id="selectForm">
<input type="checkbox" onclick="selectPhoto(1)" id="checkbox_1" class="photos" name="photos" value="1">
<input type="checkbox" onclick="selectPhoto(2)" id="checkbox_2" class="photos" name="photos" value="2">
<input type="checkbox" onclick="selectPhoto(3)" id="checkbox_3" class="photos" name="photos" value="3">
<input type="checkbox" onclick="selectPhoto(4)" id="checkbox_4" class="photos" name="photos" value="4">
<input type="checkbox" onclick="selectPhoto(5)" id="checkbox_5" class="photos" name="photos" value="5">
</form>
Upvotes: 1
Reputation: 9538
Try this:
var allValues = [];
$('input.photos').each(function(){
allValues.push($(this).val());
});
alert(allValues.join(','));
Upvotes: 2