alwaysVBNET alwaysVBNET - 2 months ago 7
jQuery Question

Select appropriate radio buttons from JSON via a loop

I am getting a

JSON
and I'm populating my form's controls with the relevant data.
All the controls work fine except the
radio buttons
. In my database I have the values for the radio buttons saved as
BIT
.

So, I'm parsing the JSON and looping for each control and assign it's value. However, it seems like I'm doing something wrong for on the
radio buttons
(maybe the case statement or my html). Any ideas?


  • I'm using jQuery 1.9



HTML

<div class="col-sm-5">
<label class="radio-inline">
<input type="radio" class="myform" value="1" name="testx">
YES
</label>
<label class="radio-inline">
<input type="radio" class="myform" value="0" name="testx">
NO
</label>

</div>

<div class="col-sm-5">
<label class="radio-inline">
<input type="radio" class="myform" value="1" name="highdanger">
YES
</label>
<label class="radio-inline">
<input type="radio" class="myform" value="0" name="highdanger">
NO
</label>
</div>


My loop

$.ajax({
type: "GET",
cache: false,
url: serviceUrl + "/ModuleTask/GetExamination" + qstring,
// beforeSend: sf.setModuleHeaders,
contentType: "application/json; charset=utf-8"
}).done(function (result) {
var oResult = JSON.parse(result);

// reset form values from json object
$.each(oResult, function (name, val) {
var $el = $('[name="' + name + '"]'),
type = $el.attr('type');

switch (type) {
case 'checkbox':
$el.attr('checked', 'checked');
break;
case 'radio':
// $el.filter('[value="' + val + '"]').attr('checked', 'checked');
//$el.attr('checked', 'checked');
// $el.prop("checked", val);
//$el.filter('[value="' + val + '"]').prop("checked", true);
// $el.filter('[value="' + true + '"]').val(1);
$el.filter('[value="' + val + '"]').prop("checked", true);
break;
default:
$el.val(val);
}
});


}).fail(function (xhr, result, status) {
alert(result);
});


AJAX response

{"ExaminationID":1,"UserID":44,"PortalID":0,"bloodcholisterol":1,"bloodldl":2,"bloodhdl":3,"bloodtriglycerides":4,"bloodglucose":5,"bodyweight":6,"bodyheight":7,"bodycircumference":8,"bodyexaminer":"DD","bodycomments":"a1","pressurestarttime":null,"pressureone":100,"pressuretwo":200,"pressurethree":300,"pressureexaminer":"B","pressurecomments":"B1","FileID":null,"agogiartiriakipiesi":null,"agogilipidia":null,"agogisakxarodidiaviti":null,"examinationcomments":"c1","highdanger":false,"sistaseis":"no sistaseis","axiologisiexaminer":"XH"}

Answer

In your radio switch case, you need to first convert your boolean to an integer. Filter by this integer value and change the checked attribute to true. Try something like this...

case 'radio':
     var i = val ? 1 : 0;
     $el.filter("[value='"+ i +"']").attr("checked", true);
     break;

Here's a JSFiddle to demonstrate.