Bobscure Bobscure - 9 days ago 4
jQuery Question

Add 'Changed' Event for each Radio Btn

I am trying to add Eventhandlers to RadioButtons, that are placed inside a jQuery DataTable. I can do this by adding it with the 'live' function like this:

$("input[name='Button0']").live("change", function() {
radioValue[0] = $(this).val();
});


The button names are generated dynamically for each DataTable Row. I have a List of questions and for every question there is a radio button group. I have tried something like this:

var countRows = 0;
$.each(questionList, function (index, value) {
var btnName = 'Button' + countRows.toString();
$("input[name="+btnName+"]").live("change", function () {
radioValue[countRows] = $(this).val();
});
countRows++;
});


However this gives me weird behaviour in filling my 'radioValue' array as it fills in only one value on a totally wrong index which shouldn't even exist.

This is my html:

<div class="content" id="IndexCompletion">
<h2>Erfassen der Leistung für Mitarbeiter: @Model.Mitarbeiter.Vorname @Model.Mitarbeiter.Nachname</h2>

<div class="dataTableSurrounding">
<table id="surveyTable">
<thead>
<th>Frage</th>
@foreach (var answerOption in Model.Survey.Questions.FirstOrDefault().AnswerOptions)
{
<th>@answerOption.Description</th>
}
</thead>
<tbody class="dynamicTryOut">
</tbody>
</table>
</div>

<br />
<br />
<div>
<input type="button" id="saveSurvey" value="Senden">
</div>




And this is the script section:

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css">
@section scripts{
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script>
var val1, val2;

var questionList = JSON.parse(JSON.stringify(@Html.Raw(Model.JsonStringQuestions)));
var answerOptionList = JSON.parse(JSON.stringify(@Html.Raw(Model.JsonStringAnswerOptions)));
var radioValue = [];

$(document).ready(function() {
var table = $('#surveyTable').DataTable({
"processing": true,
"serverSide": true,
"filter": false,
"orderMulti": false,
"ajax": {
"url": '@Url.Action("LoadSurvey", "Home")',
"type": "POST",
"datatype": "json"
},
"columns": [{ "data": "Text", "name": "Text", "autoWidth": true },
{
"render": function(data, type, full, meta) {
return '<input type="radio" class="questionButton" name="Button' + meta.row + '" value="1">';
}
},
{
"render": function(data, type, full, meta) {
return '<input type="radio" class="questionButton" name="Button' + meta.row + '" value="2">';
}
},
{
"render": function(data, type, full, meta) {
return '<input type="radio" class="questionButton" name="Button' + meta.row + '" value="3">';
}
},
{
"render": function(data, type, full, meta) {
return '<input type="radio" class="questionButton" name="Button' + meta.row + '" value="4">';
}
},
{
"render": function(data, type, full, meta) {
return '<input type="radio" class="questionButton" name="Button' + meta.row + '" value="5">';
}
}],
"language": {
"info": "Seite _PAGE_ von _PAGES_",
"infoEmpty": "Keine Einträge verfügbar",
"lengthMenu": "_MENU_ Einträge pro Seite",
"zeroRecords": "Keine Einträge gefunden",
"infoFiltered": "(filtered from _MAX_ total records)",
"processing": "Lade Formular",
"paginate": {
"next": "Weiter",
"previous": "Zurück"
}
}
});

$("#saveSurvey").click(function() {
$('<form action=@Url.Action("SaveSurvey") method="POST">' +
'<input type="hidden" name="surveyId" value="' + @Model.Survey.Id + '">' +
'<input type="hidden" name="val1" value="' + val1 + '">' +
'<input type="hidden" name="val2" value="' + val2 + '">' +
'</form>').submit();
});

var counters = 0;
$.each(questionList, function (index, value) {
$('input[name="Button' + counters + '"]').on('change', function () {
alert("worked");
radioValue[counters] = $(this).val();
});
counters++;
});
});
</script>
}


Any ideas what could be the problem?

Answer

I fixed the weird counting behaviour by calling a user defined function inside a for loop like this:

        for (var i = 0; i < questionArr.length; i++) {
            attachChangeEvent(i);
        } 


        function attachChangeEvent(index) {
            $('input[name="Button' + index + '"]').live('change', function () {
                radioValue[index] = $(this).val();
            });
        }

It seems that introducing a counter and using the $.each() loop creates unwanted behaviour. Splitting the counting and the adding of the event resolves this problem.

But i stil didn't manage to get .on()to work.

Thanks for your ideas.