mercredi 25 mars 2015

how do i get the checkbox value in ajax/jquery when using spring form


I have a group of checkboxes deefined by path deliveryStatus as shown below



<form:checkbox path="deliveryStatus" value="notDelivered"/>
<form:checkbox path="deliveryStatus" value="delivered"/>


I read two examples which are very nice


Example #1


Example #2 from StackOverflow


I notice the ID comes as deliveryStatus1 and deliveryStatus2 and not deliveryStatus therefore approach mentioned in Example #1 does not work for me directly. Also when using the solution mentioned in example #2 (considering the parent tag ID to be deliveryStatus) I do not get any result.



$('#deliveryStatus').is(":checked");


returns false and



$('#deliveryStatus').val();


gives me undefined


What is the correct way to get the selected/checked checkbox for my form(deliveryStatus) in jquery/ajax.


I noticed below code works after I realized IDs to be deliveryStatus1 and deliveryStatus2



var deliverystatus = $('#deliveryStatus1').val();
alert( 'deliverystatus' );
deliverystatus = $('#deliveryStatus1').is(":checked");
alert( deliverystatus );
deliverystatus = $('#deliveryStatus2').is(":checked");
alert( deliverystatus );


But do not feel this is the correct way to get the checked option. Reason being there are multiple checkboxes.


Reading the Example #1 I am considering there should be a better way to read those multiple checkboxes with same path value




Update to Question


Explicitly adding ID like below



<form:checkbox path="deliveryStatus" id="deliveryStatus" value="notDelivered"/>
<form:checkbox path="deliveryStatus" id="deliveryStatus" value="delivered"/>


allows me to get value by



$('#deliveryStatus:checked').val();


This is valid only if there is one selection. Therefore may not be very correct when there is multiple selection





Aucun commentaire:

Enregistrer un commentaire