I am having a problem and after hours of searching for answers and playing around with it I cannot get it to work.
My problem. I have a MYSQL database. When I pull my "boolean" data from the database via PHP it is just fine. PHP interprets the "strings" of 1's and 0's as True and False. However, when I retrieve this data to populate a form with Ajax I run into a problem.
The string comes out as: {"id":"478","name":"aaaa","manager":"385","usertype":"0","typeone":"0","typetwo":"1","typethree":"1"}
That is just fine. Until I try to populate a form with the data using:
$.each(data, function (name, val) {
var $el = $('[id="e' + name + '"]'),
type = $el.attr('type');
switch (type) {
case 'checkbox':
$el.filter('[value="' + Boolean(val) + '"]').attr('checked', 'checked');
break;
case 'radio':
$el.filter('[value="' + val + '"]').attr('checked', 'checked');
break;
default:
$el.val(val);
}
});
On this http://jsfiddle.net/z66XF/11/ you can see that data used to check off the check boxes doesn't work when it comes from my database with the "boolean" values given as strings.
"0" ends up being evaluated as true.
Is there any way to convert this or have javascript see it as boolean?
You can use Unary Plus Operator to convert the string to a number
Boolean(+val)
Basic Example:
var one = "1";
var zero = "0";
console.log("one", one, Boolean(+one)); //one "1" true
console.log("zero", zero, Boolean(+zero)); //zero 0 false
JSFiddle: