Reputation: 2642
I have list of radio button in my views like this :
<input type="radio" name="questionOpt[1]" value="Very Satisfied-1-1" />
<input type="radio" name="questionOpt[1]" value="Satisfied-1-2" />
<input type="radio" name="questionOpt[1]" value="Neutral-1-3" />
<input type="radio" name="questionOpt[1]" value="Dissatisfied-1-4" />
<input type="radio" name="questionOpt[1]" value="Very Dissatisfied-1-5" />
<input type="radio" name="questionOpt[2]" value="Very Satisfied-2-1" />
<input type="radio" name="questionOpt[2]" value="Satisfied-2-2" />
<input type="radio" name="questionOpt[2]" value="Neutral-2-3" />
<input type="radio" name="questionOpt[2]" value="Dissatisfied-2-4" />
<input type="radio" name="questionOpt[2]" value="Very Dissatisfied-2-5" />
<input type="submit" value="Submit" id="submit" />
When user select the radio button , I want to write the value of radio button to array and then pass it to the controller of my asp.net mvc project.
This is what I have tried :
<input type="hidden" id="resultSelect" name="resultSelect" value="1,2,3,4,5"/>
<script type="text/javascript">
var clicks = new Array();
$(document).ready(function () {
for (var i = 1; i <= count_; i++) {
$("input:radio[name='questionOpt["+i+"]']").click(function () {
clicks.push($(this).val());
});
}
});
$("#submit").click(function () {
for (var y = 0; y<clicks.length; y++) {
$("#resultSelect").val(clicks[y]);
}
});
</script>
I write in my controller like this :
string result= frm["resultSelect"].ToString();
When I click on radio button Very Satisfied-1-1
and Dissatisfied-2-4
, Then when I debug it, there's only Dissatisfied-2-4
in result
string.
Could anyone tell me how could I get two of radio button value Very Satisfied-1-1
and Dissatisfied-2-4
as an array ["Very Satisfied-1-1","Dissatisfied-2-4"]
in result
string of my controller.
Thanks.
Upvotes: 1
Views: 2853
Reputation: 144729
You are overwriting values in the for loop, you can use serailizeArray
method:
Encode a set of form elements as an array of names and values.
$("#submit").click(function () {
var arr = $('input[type=radio]').serializeArray();
$("#resultSelect").val(arr);
});
Upvotes: 1
Reputation: 27382
Try
$("#submit").click(function ()
{
var selectedIdsStr = clicks.join(",");
$("#resultSelect").val(selectedIdsStr);
});
and please also wrap above code inside document.ready
Upvotes: 2