How to serialize checkbox value through searilizedarray()? - javascript

My question is how to serialize checkbox value and textbox value together in one array through searilizedarray()...
now i am getting something like this
[{"name":"text_input","value":"kalpit"},
{"name":"wpc_chkbox[]","value":"Option one"},
{"name":"wpc_chkbox[]","value":"Option two"},
{"name":"wpc_chkboxasdf[]","value":"Option one"},
{"name":"wpc_chkboxasdf[]","value":"Option two"},
{"name":"wpc_inline_chkbox[]","value":"1"},
{"name":"wpc_inline_chkbox[]","value":"2"},
{"name":"wpc_inline_chkbox[]","value":"3"},
{"name":"wpc_radios","value":"Option one"}]
but it should be like
[{"name":"text_input","value":"kalpit"},
{"name":"wpc_chkbox[]","value":"[Option one,Option Two]"},
{"name":"wpc_chkboxasdf[]","value":"[Option one,Option Two]"},
{"name":"wpc_inline_chkbox[]","value":"[1,2,3]"},
{"name":"wpc_radios","value":"Option one"}]
i am using var form = $('.wpc_contact').serializeArray(); to get form data
this is my html sample which I am generating dynamically using drag and drop future..
<form method="POST" name="1" class="form-horizontal wpc_contact" novalidate="novalidate">
<fieldset>
<div id="legend" class="">
<legend class="">Demo</legend>
<div id="alert-message" class="alert hidden" style="color: red;"></div>
</div>
<div class="control-group">
<label class="control-label">Checkboxes</label>
<div class="controls" name="wpc_chkbox" req="yes">
<input type="checkbox" value="Option one" id="wpc_chkbox_0" name="wpc_chkbox[]" req="yes"> Option one
<input type="checkbox" value="Option two" id="wpc_chkbox_1" name="wpc_chkbox[]" req="yes"> Option two
</div>
</div>
<div class="control-group">
<div class="controls" name="wpc_inline_chkbox" req="yes">
<input type="checkbox" value="1" name="wpc_inline_chkbox[]" id="wpc_inline_chkbox_0" req="yes"> 1
<input type="checkbox" value="2" name="wpc_inline_chkbox[]" id="wpc_inline_chkbox_1" req="yes"> 2
<input type="checkbox" value="3" name="wpc_inline_chkbox[]" id="wpc_inline_chkbox_2" req="yes"> 3
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn btn-success">Button</button>
</div>
</div>
</fieldset>
</form>
Thanks in advance

Try this:
var cacheObject = {};//tmp cache for form elements name/values pairs
var serArr = $('.wpc_contact').serializeArray();
//set values of elements to cacheObject
$.each(serArr, function (arrayIndex,obj) {
if (cacheObject[obj.name]) {
cacheObject[obj.name].push(obj.value);
} else {
cacheObject[obj.name] = [obj.value];
}
});
//create new serialized array
var newSerArr = [];
$.each(cacheObject, function (key, value) {
var obj = {};
obj[key] = value;
newSerArr.push(obj);
});
console.log(newSerArr);//looks like serializeArray

This one makes a different array and elements of same name are grouped together.
var form_data = $(".wpc_contact").serializeArray();
var form_array = {}; //final array where all the values will be stored
$.each(form_data, function(i, element) {
if(jQuery('input[name="'+element.name+'"]:checked').length>0)
{
replaced = element.name.replace('[]',''); //removing [] from the input name
form_array[replaced]={};
jQuery('input[name="'+element.name+'"]:checked').each(function(j,ind){
form_array[replaced][j] = jQuery(this).val();
});
}
else
{
form_array[element.name] = element.value;
}
});
console.log(form_array);
You can access as:
alert(form_array['wpc_chkbox'][0]); //no '[]' in the key

Related

HTML Form Values don't push to JavaScript array

Ok, so I am trying to push the value of an HTML form input to a JavaScript array. When I load the page and submit values through the form, it returns empty strings in the array. I don't understand why this is happening. Thank you for your help.
Relevant HTML:
<form>
<div class="form-group">
<label for="name1">Name: </label>
<input type="text" class="form-control b" id="nameone">
<label for="pref1">Preferences: </label>
<input type="text" class="form-control a" id="prefone"> </div>
<div class="form-group">
<label for="name2">Name: </label>
<input type="text" class="form-control c" id="nametwo">
<label for="pref2">Preferences: </label>
<input type="text" class="form-control a" id="preftwo"> </div>
<div class="form-group">
<label for="name3">Name: </label>
<input type="text" class="form-control d" id="namethree">
<label for="pref3">Preferences: </label>
<input type="text" class="form-control a" id="prefthree"> </div>
<div class="form-group">
<label for="name4">Name: </label>
<input type="text" class="form-control e" id="namefour">
<label for="pref4">Preferences: </label>
<input type="text" class="form-control a" id="preffour"> </div>
<!-- ... -->
<button type="submit" class="btn btn-primary" id="sbm">Submit</button>
</form>
Relevant JavaScript:
var table1 = [];
var table2 = [];
var table3 = [];
var table4 = [];
var names = [];
var pref = [];
// ...
function namesdefine() {
names.push(document.getElementById('nameone').value);
names.push(document.getElementById('nametwo').value);
names.push(document.getElementById('namethree').value);
names.push(document.getElementById('namefour').value);
names.push(document.getElementById('namefive').value);
names.push(document.getElementById('namesix').value);
names.push(document.getElementById('nameseven').value);
names.push(document.getElementById('nameeight').value);
names.push(document.getElementById('namenine').value);
names.push(document.getElementById('nameten').value);
names.push(document.getElementById('nameeleven').value);
names.push(document.getElementById('nametwelve').value);
names.push(document.getElementById('namethirteen').value);
names.push(document.getElementById('namefourteen').value);
names.push(document.getElementById('namefifthteen').value);
names.push(document.getElementById('namesixteen').value);
names.push(document.getElementById('nameseventeen').value);
names.push(document.getElementById('nameeighteen').value);
names.push(document.getElementById('namenineteen').value);
names.push(document.getElementById('nametwenty').value);
names.push(document.getElementById('nametwentyone').value);
names.push(document.getElementById('nametwentytwo').value);
names.push(document.getElementById('nametwentythree').value);
names.push(document.getElementById('nametwentyfour').value);
console.log(names);
var testvar = document.getElementById('nameone').value;
console.log(testvar);
console.log("Look here please");
}
document.getElementById('sbm').onclick = namesdefine();seat(document.getElementsByClassName('a').value);check();changeHTML();
console.log(table1);
console.log(table2);
console.log(table3);
console.log(table4);
console.log("second call");
You're calling the namesdefine() function when you assign to .onclick. You should be assigning the function to .onclick, so leave out the () after it.
document.getElementById('sbm').onclick = namesdefine;
Either use:
document.getElementById('sbm').onclick = namesdefine;
Or
document.getElementById('sbm').addEventListener('click', namesdefine);
If you need to call them all, use this:
document.getElementById('sbm').onclick = function () {
namesdefine();
seat(document.getElementsByClassName('a').value);
check();
changeHTML();
}
And it's always a good practice to check for null after getElementById()
Try to get your data in a loop.
You can use getElementByTagName or getElementByClassName.
var elements = document.getElementsByTagName("input")
for (var i = 0; i < elements.length; i++) {
//Create array here arr.push(elements[i].value);
}
You can call that in your click function.
Hope that helps.

How to use checkbox with nested ng-repeat in angularjs

Hello everyone i have faced some problem in case of nested checkbox uses. In my problem i m stuck on to how to use IncludeAll on click checkbox. If checkbox value is true then it's give me a value of that. if IncludeAll checkbox is true then all checkbox will be selected and show the value of all in Array. and if one of the checkbox is false then IncludeAll checkbox false..But in Case the other checkbox will be selected.
This is my Fiddle Link : http://jsfiddle.net/0x4396pu/1/
Here is my Html Code:
<form action="#" ng-controller='MyCtrl'>
<div class="control-group" ng-repeat="story in stories">
<br>
<input type="checkbox" ng-model="story.selectionAll">
<label class="control-label">IncludeAll {{story}}</label>
<div class="controls">
<label class="checkbox inline" ng-repeat="browser in browsers">
<input type="checkbox" value="{{browser}}"
ng-model="selection[story].browsers[browser]"
ng-checked="story.selectionAll">
{{browser}}
</label>
</div>
</div>
</div>
<pre>{{selection | json }}</pre>
</form>
Here is my Controller file :
function MyCtrl($scope) {
$scope.stories = ['1', '2', '3'];
$scope.browsers = ['IE', 'Chrome', 'Firefox','Safari','Opera'];
$scope.selection = {};
angular.forEach($scope.stories, function(story) {
$scope.selection[story] = {
browsers: {},
};
});
}
Thanks in Advance.
I am answer my own Question. But anyway Here is Answer how to select Checkbox in Nested ng-repeat.i think It's Help you Thanks.
Http Plunkr LInk http://plnkr.co/edit/OQxi53xtVKOgToPhzDUZ?p=preview
Here is Html Code:
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.4
/angular.min.js">
</script>
<script src="script.js"></script>
</head>
<body>
<form action="#" ng-controller='detailContrller'>
<div class="control-group" ng-repeat="story in stories"> <br>
<h4> Enter Data </h4>
Name : <input type="text" data-ng-model="selection[story].Name1"
placeholder="Enter Name"> <br>
Address : <input type="text" data-ng-model="selection[story].Name2"
placeholder="Enter Address"> <br>
City : <input type="text" data-ng-model="selection[story].Name3"
placeholder="Enter City"> <br>
Phone : <input type="text" data-ng-model="selection[story].Name4"
placeholder="Enter Phone "> <br>
State : <input type="text" data-ng-model="selection[story].Name5"
placeholder="Enter State"> <br>
<input type="checkbox" ng-model="selection[story].all"
ng-change="updateAll(story)">
<label class="control-label">IncludeAll {{story}}</label>
<div class="controls">
<label class="checkbox inline" ng-repeat="browser in browsers">
<input type="checkbox" value="{{browser}}"
ng-model="selection[story].browsers[browser]"
ng-change="checkChange(browser)"
> {{browser}}
</label>
</div>
</div>
<button type="button" data-ng-click="save()">Save</button>
<pre>{{selection | json}}</pre>
</form>
</body>
</html>
Here is my Controller
var app = angular.module("myApp",[]);
app.controller('detailContrller', function($scope){
$scope.stories = [];
$scope.browsers = ['IE', 'Chrome', 'Firefox','Safari','Opera'];
$scope.selection = {};
$scope.details = {};
var checked;
$scope.updateAll = function (story) {
checked = $scope.selection[story].all;
$scope.browsers.forEach(function (browser) {
$scope.selection[story].browsers[browser] = checked;
});
};
for(var i = 0; i< 3; i++) {
$scope.stories.push(i+1);
}
$scope.checkChange = function (browser) {
for(var i =0; i< $scope.stories.length; i++){
if(!$scope.stories[i].selected){
checked = false
return false;
}
}
}
angular.forEach($scope.stories, function(storgy) {
$scope.selection[storgy] = {
browsers: {}
};
});
$scope.save = function () {
console.log($scope.selection);
}
})
Your "include all" checkbox is trying to set .selectionAll property on a String (story in stories gives you a String).
You can't use ng-checked to somehow "work together" with ng-model. If you want your "include all" checkbox to select all subordinate checkboxes and vice versa, you'll need to watch the changes and provide some logic connecting the two things in your controller.
For example, if you want change of the "include all" checkbox value to influence other checkboxes, you'd have to do something like
<input type="checkbox" ng-model="selection[story].all" ng-change="updateAll(story)">
and in your controller
$scope.updateAll = function (story) {
var checked = $scope.selection[story].all;
$scope.browsers.forEach(function (browser) {
$scope.selection[story].browsers[browser] = checked;
});
};
and handle changes of the individual checkboxes in a similar fashion.

how to store the checked value from checked box and radio box in local storage

I am using JQuery Mobile
I want to display the value in another page which i get from local storage
It Should been check which is been checked in page1
In HTML5:-
<div data-role="page" id="page1">
<div data-role="content">
<div data-role="fieldcontain">
<form>
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Levels:</legend>
<input type="checkbox" value="One" name="one" id="checkbox-h-2a" class="custom1">
<label for="checkbox-h-2a">One</label>
<input type="checkbox" value="None" name="one" checked="checked" id="checkbox-h-2c" class="custom1">
<label for="checkbox-h-2c">None</label>
</fieldset>
</form>
</div>
<div data-role="fieldcontain">
<form>
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Mode:</legend>
<input type="radio" name="Two" id="radio-choice-h-2a" value="On" checked="checked" class="custom2">
<label for="radio-choice-h-2a">On</label>
<input type="radio" name="Two" id="radio-choice-h-2b" value="Off" class="custom2">
<label for="radio-choice-h-2b">Off</label>
</fieldset>
</form>
</div>
</div>
</div>
<div data-role="page" id="page2">
<div data-role="content">
<div data-role="fieldcontain">
<form>
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Levels:</legend>
<input type="checkbox" name="checkbox-h-2a" id="checkbox-h-2a" class="custom1">
<label for="checkbox-h-2a">One</label>
<input type="checkbox" name="checkbox-h-2c" id="checkbox-h-2c" class="custom1">
<label for="checkbox-h-2c">None</label>
</fieldset>
</form>
</div>
<div data-role="fieldcontain">
<form>
<fieldset data-role="controlgroup" data-type="horizontal">
<legend>Mode:</legend>
<input type="radio" name="radio-choice-h-2" id="radio-choice-h-2a" value="on" class="custom2">
<label for="radio-choice-h-2a">Steward</label>
<input type="radio" name="radio-choice-h-2" id="radio-choice-h-2b" value="off" class="custom2">
<label for="radio-choice-h-2b">Guest</label>
</fieldset>
</form>
</div>
</div>
</div>
In Jquery:-
function getRadioCheckedValue(radio_name)
{
var oRadio = $("input[type='radio']");
for(var i = 0; i < oRadio.length; i++)
{
if(oRadio[i].checked)
{
//return oRadio[i].value;
localStorage.setItem("mode", oRadio[i].value);
}
}
return '';
}
function showSelectedNames(){
var count = $("#checkid input:checked").length;
var str = '';
for(i=0;i<count;i++){
if(i == count-1){
str += $("#checkid input:checked")[i].value;
localStorage.setItem("level", str);
}
else{
str += $("#checkid input:checked")[i].value+',';
localStorage.setItem("level", str);
}
}
//alert("You selected----"+str);
}
Now Plz help me out how to set the value in Page 2 which is been checked in Page1
The simplest way is to store values of checkboxes and radio buttons into an array and then save it to localStorage. However, note that localStorage doesn't accept arrays, so you need to JSON.stringify() before saving it into localStorage and then JSON.parse() to convert it back into a readable array.
Here is how you can collect values of all checkboxes and radio buttons, store them and then read them on next page.
$(document).on("pagebeforehide", "[data-role=page]", function () {
// variables
var elements = [],
id = '',
value = '';
// push values of checkboxes and radio buttons into an array
$("[type=checkbox], [type=radio]", this).each(function () {
id = $(this)[0].id;
value = $(this).prop("checked");
elements.push({
"id": id,
"value": value
});
});
// convert array into a string
// in order store it into localStorage
localStorage["values"] = JSON.stringify(elements);
});
$(document).on("pagebeforeshow", "[data-role=page]", function () {
// active page
var active = $.mobile.activePage;
// parse array of checkboxes and radio buttons
var read_array = JSON.parse(localStorage["values"]);
// check/uncheck checkboxes and radio buttons
$.each(read_array, function (e, v) {
var check_id = "#" + v.id,
check_value = v.value;
$(check_id, active).prop("checked", check_value).checkboxradio("refresh");
});
});
Note: elements id should be the same on other pages.
Demo

Create a link based on values from a Html form and redirect them to it

What I'm trying to do is to redirect people to a link depending of what they have summited on the form (the link is built using the values from the form fields)
This is the Form:
<form id="form">
<div class="formbox">
<div class="radio-toolbar">
<input type="radio" id="iconapp1" name="department" value="1250"/>
<label for="iconapp1">PP</label><br>
<input type="radio" id="iconapp2" name="department" value="944"/>
<label for="iconapp2">EP</label><br>
</div>
<div class="radio-bar1">
<input type="radio" id="enginemake1" name="enginemake" value="6"/>
<label for="enginemake1"> Chevrolet</label><br>
<input type="radio" id="enginemake2" name="enginemake" value="8"/>
<label for="enginemake2"> Chrysler</label><br>
</div>
<div class="bodyvertdivision1"></div>
<div class="radio-bar3">
<select name="powerrange">
<option id="powerrange1" value="28">100</option>
<option id="powerrange2" value="128">200</option>
<option id="powerrange3" value="228" selected>300</option>
</select>
</div>
<div class="bodyvertdivision1"></div>
<div class="radio-bar4">
<input type="radio" id="location1" name="location" value="store"/>
<label for="location1"> America (NT - ST)</label><br>
<input type="radio" id="location2" name="location" value="store.au"/>
<label for="location2"> Australia and Oceania</label><br>
</div>
<div class="radio-bar2">
<input onclick="goToPage();" type="button" class="buttonmyapp" value="Submit" />
</div>
</div>
</form>
The link I'm trying to build using the values selected will look like this:
http://{location}.mydomain.com/product-catalog.aspx?section=-{department}-{enginemake}-{powerrange}-
Each bracketed section needs to be replaced by the value of the select with the corresponding name.
First include the jquery library link or download js and link
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
function goToPage(){
var location = $('input[name=location]:checked').val();
var department = $('input[name=department]:checked').val();
var enginemake = $('input[name=enginemake]:checked').val();
var powerrange = $('select[name=powerrange]').val();
window.location.href = "http://"+location+".mydomain.com/product-catalog.aspx?section=-"+department+"-"+enginemake+"-"+powerrange+"-";
}
</script>
After the goToPage function on the submit button validates the response change the src attribute of the form should work fine.
So in jQuery it should look something like
var location = $('input[name=location]:checked', '.radio-bar4').val();
var dept = $('input[name=location]:checked', '.radio-bar4').val();
var engine = $('input[name=enginemake]:checked', '.radio-bar1').val();
var power = $('powerrange').val() ;
var domain = "http://"+ location+".mydomain.com/product-catalog.aspx?section=-"+dept+"-"+engine+"-"+power+"-";
$("#form").attr("action", domain);
you can try this
HTML
<select id="powerrange" name="powerrange">
JAVASCRIPT
function goToPage()
{
var location;
var department;
var enginemake;
var powerrange;
pName = document.getElementById('powerrange');
powerrange = pName.options[pName.selectedIndex].value;
var form = document.getElementById('form');
var ele = form.getElementsByTagName('input');
for(var i=0;i<ele.length;i++)
{
if(ele[i].getAttribute('type')=='checkbox')
{
if(ele[i].getAttribute('name')=='department')
{
if(ele[i].checked)
department = ele[i].value;
}
else if(ele[i].getAttribute('name')=='enginemake')
{
if(ele[i].checked)
enginemake = ele[i].value;
}
else if(ele[i].getAttribute('name')=='location')
{
if(ele[i].checked)
location = ele[i].value;
}
else;
}
}
var url = "http://"+ location+".mydomain.com/product-catalog.aspx?section=-"+department+"-"+enginemake+"-"+powerrange+"-";
form.setAttribute('action',url);
form.submit();
}

How to fill form with JSON?

I get ajax response as JSON and need to fill a form with it. How to do that in jQuery or something else ? Is something better than using $(json).each() ?
JSON:
{
"id" : 12,
"name": "Jack",
"description": "Description"
}
Form to fill
<form>
<input type="text" name="id"/>
<input type="text" name="name"/>
<input type="text" name="description"/>
</form>
var json={
"id" : 12,
"name": "Jack",
"description": "Description"
};
for(key in json)
{
if(json.hasOwnProperty(key))
$('input[name='+key+']').val(json[key]);
}
srry i thought it was the id property that was set.
here: http://jsfiddle.net/anilkamath87/XspdN/
Came here searching for a solution that didn't involve jQuery or a brunch of DOM scaning, but didn't find one... so here is my vanilla js solution brought to you other guys that probably ditched jQuery long ago.
const data = {
"id" : 12,
"name": "Jack",
"description": "Description",
"nonExisting": "works too"
}
const { elements } = document.querySelector('form')
for (const [ key, value ] of Object.entries(data) ) {
const field = elements.namedItem(key)
field && (field.value = value)
}
<form>
<input type="text" name="id"/>
<input type="text" name="name"/>
<input type="text" name="description"/>
</form>
Assuming data is the JSON object, you could use this inside the $.getJSON callback:
var $inputs = $('form input');
$.each(data, function(key, value) {
$inputs.filter(function() {
return key == this.name;
}).val(value);
});
Pretty simple in pure JavaScript:
https://jsfiddle.net/ryanpcmcquen/u8v47hy9/
var data = {
foo: 1,
bar: 2
};
var inputs = Array.prototype.slice.call(document.querySelectorAll('form input'));
Object.keys(data).map(function (dataItem) {
inputs.map(function (inputItem) {
return (inputItem.name === dataItem) ? (inputItem.value = data[dataItem]) : false;
});
});
<form>
<input name="foo">
<input name="bar">
</form>
Edit: This also works with other inputs such as select, simply by replacing document.querySelectorAll('form input') with document.querySelectorAll('form input, form select').
This also gets around the global leak in this answer:
https://stackoverflow.com/a/6937576/2662028
jQuery Populate plugin and code proposed by #Mathias inspired me to make my own plugin:
Here my myPopulate plugin code. It use attr parameter as name of elements attribute on to use for identifying them.
(function($) {
$.fn.myPopulate = function(json, attr) {
var form = $(this);
$.each(json, function(key, value) {
form.children('[' + attr + '="' + key + '"]').val(value);
});
};
})(jQuery);
Using:
{
"id" : 12,
"name": "Jack",
"description": "Description"
}
form1 (matching by name attribute):
<form>
<input type="text" name="name" />
<input type="text" name="id" />
<textarea type="text" name="description" />
</form>
$('#form1').myPopulate(json, 'name');
form2 (matching by alt attribute):
<form id="form2">
<input type="text" name="nick" alt="name" />
<input type="text" name="identifier" alt="id" />
<textarea type="text" name="desc" alt="description" />
</form>
$('#form2').myPopulate(json, 'alt');
I'm using this method with iCheck elements. This method can work native check and radio inputs.
populateForm(frm, data) {
console.log(data);
$.each(data, function(key, value) {
var ctrl = $("[name=" + key + "]", frm);
switch (ctrl.prop("type")) {
case "radio":
if (
ctrl.parent().hasClass("icheck-primary") ||
ctrl.parent().hasClass("icheck-danger") ||
ctrl.parent().hasClass("icheck-success")
) {
// raido kutularında aynı isimden birden fazla denetçi olduğu için bunları döngüyle almak lazım
// multiple radio boxes has same name and has different id. for this we must look to each html element
$.each(ctrl, function(ctrlKey, radioElem) {
radioElem = $(radioElem);
console.log(radioElem);
console.log(radioElem.attr("value"));
if (radioElem.attr("value") == value) {
radioElem.iCheck("check");
} else {
radioElem.iCheck("uncheck");
}
});
} else {
$.each(ctrl, function(ctrlKey, radioElem) {
radioElem = $(radioElem);
console.log(radioElem);
console.log(radioElem.attr("value"));
if (radioElem.attr("value") == value) {
radioElem.attr("checked", value);
} else {
radioElem.attr("checked", value);
}
});
}
break;
case "checkbox":
if (
ctrl.parent().hasClass("icheck-primary") ||
ctrl.parent().hasClass("icheck-danger") ||
ctrl.parent().hasClass("icheck-success")
) {
if (ctrl.attr("value") == value) {
ctrl.iCheck("check");
} else {
ctrl.iCheck("uncheck");
}
} else {
ctrl.removeAttr("checked");
ctrl.each(function() {
if (value === null) value = "";
if ($(this).attr("value") == value) {
$(this).attr("checked", value);
}
});
}
break;
default:
ctrl.val(value);
}
});
}
Example form:
<form id="form1">
<div className="form-group row">
<label className="col-sm-3 col-form-label">
{window.app.translate(
"iCheck Radio Example 1"
)}
</label>
<div className="col-sm-9">
<div className="icheck-primary">
<input
type="radio"
id="radio1_0"
name="radio1"
value="0"
/>
<label for="radio1_0">
{window.app.translate(
"Radio 1 0"
)}
</label>
</div>
<div className="icheck-primary">
<input
type="radio"
id="radio1_1"
name="radio1"
value="1"
/>
<label for="radio1_1">
{window.app.translate(
"Radio 1 1"
)}
</label>
</div>
<div className="icheck-primary">
<input
type="radio"
id="radio1_2"
name="radio1"
value="2"
/>
<label for="radio1_2">
{window.app.translate(
"Radio 1 2"
)}
</label>
</div>
</div>
</div>
<div className="form-group row">
<label className="col-sm-3 col-form-label">
{window.app.translate(
"iCheck Radio Example 2"
)}
</label>
<div className="col-sm-9">
<div className="icheck-primary">
<input
type="radio"
id="radio2_0"
name="radio2"
value="0"
/>
<label for="radio2_0">
{window.app.translate(
"Radio 2 0"
)}
</label>
</div>
<div className="icheck-primary">
<input
type="radio"
id="radio2_1"
name="radio2"
value="1"
/>
<label for="radio2_1">
{window.app.translate(
"Radio 2 1"
)}
</label>
</div>
<div className="icheck-primary">
<input
type="radio"
id="radio2_2"
name="radio2"
value="2"
/>
<label for="radio2_2">
{window.app.translate(
"Radio 2 2"
)}
</label>
</div>
</div>
</div>
<div className="form-group row">
<label
htmlFor="ssl"
className="col-sm-3 col-form-label"
>
{window.app.translate("SSL")}
</label>
<div className="col-sm-9">
<div className="form-group row">
<div className="col-sm-12">
<div className="icheck-primary d-inline">
<input
type="checkbox"
id="ssl"
name="ssl"
value="1"
/>
<label for="ssl" />
</div>
</div>
</div>
</div>
</div>
</form>
Example json data:
{
"radio1": "3",
"radio2": "1",
"ssl": "0"
}
Edit: I tried populate plugin but it doesn't working with iCheck and other things for example select2, chosen, etc...
You might want to take a look at the jQuery Populate plugin.
Although if this is the only use case you have, you might as well do it manually.
Just use a JSON plugin for jQuery - such as jquery-json.
You might also consider usage of jQuery templates for that purpose:
http://api.jquery.com/jQuery.template/
First you need to parse the JSON string so that you get an object that you can use:
var o = $.parseJSON(json);
(Note: You can also specify the data type 'json' in the AJAX call, then it will be parsed into an object already when you get the result.)
Then you can loop throught the properties in the object:
$.each(o, function(key, value){
$('form [name=' + key + ']').val(value);
});
I haven't seen a solution that accounts for a form with nested properties.
Here it is.
//pass in the parent object name, if there is one
let parentName = 'optional';
SyncJsonToForm(data, parentName);
function SyncJsonToForm(obj, path = '') {
let subpath = path === '' ? path : path + '.';
$.each(obj, function (key, value) {
let jsonPath = subpath + key;
// to debug a particular field (or multiple fields), replace the following JsonPath(s) with the desired property(ies)
if ([''].includes(jsonPath)) {
console.log(jsonPath);
debugger;
}
// update the value for the jsonPath
$(`[name="${jsonPath}"]`).val(value);
if (typeof value === "object") {
SyncJsonToForm(value, jsonPath);
}
});
}

Categories