Reputation: 323
I have check-boxes of "Apartment","House" etc. I want to collect the values of these check-boxes into an array and send that array to controller using json. Since I'm new to jquery I don't know how to put those values into an array using jquery ?
<script type="text/javascript">
$(document).ready(function () {
var arr = $("#hiddenroomdetails").val().split(",");
$('input[type=checkbox]').each(function () {
if ($.inArray($(this).val(), arr) > -1) {
$(this).attr("checked", "checked");
}
});
});
</script>
$.getJSON('@Url.Action("testcata", "home")' + '?property=' + selectedvalue +"&chkd="+checkedValues
function (data) {
//code
})
Upvotes: 1
Views: 76
Reputation: 1253
You can try this:
$('button').click(function() {
var Arr = [];
$('.check:checked').map(function() {
Arr.push(this.value);
});
alert(Arr);
alert(Arr[0]);
})
Upvotes: 0
Reputation: 193261
Pretty common way to do it using jQuery is by using map
method. For example:
var checkedValues = $('.check:checked').map(function() {
return this.value;
}).get();
Upvotes: 4
Reputation: 3797
Lets say if you give these checkboxes a class called "selectbox" and do the following code:
var selected = [];
$('.selectbox').click(function(){
if( $.inArray($(this).val(), selected) > -1 ){
var index = selected.indexOf( $(this).val() );
selected.splice( index, 1 );
}
else {
selected.push( $(this).val() );
}
}
This will fire an event when the checkboxes are clicked. It then checks if the value already exists in the "selected"-array. if it exists, it removes it (checkbox is unchecked). If it doesnt exist (checkbox is checked), it ads it.
Then you can pass on the "selected" array to the json function
Upvotes: 1