I have a form like so that collects information about a users car:
<form id="car" action="" method="">
<section class="inputContainer">
<section class="carInfo">
<input type="text" name="Make" class="make" />
<input type="text" name="Model" class="model" />
<input type="text" name="Year" class="year" />
<input type="text" name="Color" class="color" />
</section>
</section>
<input type="hidden" name="AllCarData" />
<a class="addAnotherCar" href="#">Add another car</a>
<input type="submit" value="Submit" />
</form>
When the user clicks the 'Add another car' link, my JS duplicates the 'carInfo' group of inputs and appends it to 'inputContainer'; creating a new set of form inputs like so:
<form id="car" action="" method="">
<section class="inputContainer">
<section class="carInfo">
<input type="text" name="Make" class="make" />
<input type="text" name="Model" class="model" />
<input type="text" name="Year" class="year" />
<input type="text" name="Color" class="color" />
</section>
<section class="carInfo">
<input type="text" name="Make" class="make" />
<input type="text" name="Model" class="model" />
<input type="text" name="Year" class="year" />
<input type="text" name="Color" class="color" />
</section>
</section>
<input type="hidden" name="AllCarData" />
<a class="addAnotherCar" href="#">Add another car</a>
</form>
Once the user clicks submit, I want to parse the form into a JSON object and inject it into a hidden input field. JSON for two cars should look like this:
[{ "Make" : "Mazda" , "Model": "Protege" , "Year" : "2002" , "Color" : "Red" } , { "Make" : "Toyota" , "Model": "Camery" , "Year" : "2012" , "Color" : "Blue" }]
I am currently getting the input's name to serve as the key and the entered value as the value. I have the following function built:
CreateJson: function () {
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
var carDataString = JSON.stringify($('.inputContainer input').serializeObject());
console.log(carDataString);
$("input[name='AllCarData']").val(carDataString);
}
};
********The only problem is that since the additional inputs that are duplicated when a user chooses to add another car use the same 'name', my JSON is only outputting one set of values insead of multiple (when multiple cars are added). http://jsfiddle.net/njacoy/jLopamk7/
Note: I am using the jQuery validate plugin to validate this form. It's set to look for input names.
Thanks!
Try this -
$.fn.serializeObject = function (data) {
var els = $(this).find(':input').get();
if (typeof data != 'object') {
// return all data
data = {};
$.each(els, function () {
if (this.name && !this.disabled && (this.checked || /select|textarea/i.test(this.nodeName) || /text|hidden|password/i.test(this.type))) {
data[this.name] = $(this).val();
}
});
return data;
}
};
$("#car").submit(function () {
var data = [];
$(this).find(".inputContainer section").each(function () {
data[data.length] = $(this).serializeObject();
})
var carDataString=JSON.stringify(data);
console.log(carDataString);
$("input[name='AllCarData']").val(carDataString);
return false
});
here's the working fiddle http://jsfiddle.net/vikrant47/jLopamk7/4/
You would serialise the inputs in each section separately, then get them as an array and use stringify on that:
var carDataString = JSON.stringify(
$('.inputContainer section').map(function(i, o){
return o.find('input').serializeObject();
}).get()
);
Related
i want to get all of this input values to my budget app
but i have problem to get values of the radio button because it says its undefined. i create global function to get by radio button value. but the others is in javascript module.
https://jsfiddle.net/8k3gw7ty/
<div class="button_income">
<input type="radio" name="type" value="inc" id="incomebtn" onclick="getButtonValue();" checked>
<label for="incomebtn" class="income-btn">+ Add Income</label>
</div>
<div class="button_expense">
<input type="radio" name="type" value="exp" id="expensebtn" onclick="getButtonValue();">
<label for="expensebtn" class="expense-btn">+ Add Expense</label>
</div>
<div class="desc_input">
<label class="labelinput" for="input-desc">Your Income/Expense Description</label>
<input id="input-desc" type="text" class="input_description" placeholder="Salary">
</div>
<div class="value_input">
<label class="labelinput" for="input-val">Value of Income/Expense</label>
<input id="input-val" type="number" class="input_value" placeholder="Rp. 100.000">
</div>
Actually there was no default value for your val variable. Since val will only get value when you click on the checkbox (according to your code).
Also you were returning val which isn't necessary. I've also removed the budgetController.
Hope this'll help.
let val = 'inc'; // default value
function getButtonValue() {
var type = document.getElementsByName("type");
if (type[0].checked) {
val = type[0].value
} else if (type[1].checked) {
val = type[1].value
}
}
const domController = (function() {
return {
getInput: function() {
return {
type: val,
description: document.querySelector(".input_description").value || 0,
value: parseFloat(document.querySelector(".input_value").value) || 0
}
}
}
})();
const controller = (function( UI) {
var ctrlAddItem = function() {
var input = UI.getInput();
console.log(input);
}
document.querySelector(".addbtn").addEventListener("click", ctrlAddItem)
document.addEventListener("keypress", function(event) {
if (event.keyCode === 13 || event.which === 13) {
ctrlAddItem();
}
});
})( domController);
<div class="button_income">
<input type="radio" name="type" value="inc" id="incomebtn" onclick="getButtonValue();" checked>
<label for="incomebtn" class="income-btn">+ Add Income</label>
</div>
<div class="button_expense">
<input type="radio" name="type" value="exp" id="expensebtn" onclick="getButtonValue();">
<label for="expensebtn" class="expense-btn">+ Add Expense</label>
</div>
<div class="desc_input">
<label class="labelinput" for="input-desc">Your Income/Expense Description</label>
<input id="input-desc" type="text" class="input_description" placeholder="Salary">
</div>
<div class="value_input">
<label class="labelinput" for="input-val">Value of Income/Expense</label>
<input id="input-val" type="number" class="input_value" placeholder="Rp. 100.000">
</div>
<button><i class="fas fa-check addbtn">Save</i></button>
I have this submit button on my form with a jQuery action to open a window depending on the users choice. However, I just want the window to open if the fields are filled. I have this code and I want to merge it with an if.
$(function() {
$('#chkveg').multiselect({
includeSelectAllOption: true
});
$('#btnget').click(function() {
window.open($('#chkveg').val());
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="http://formmail.kinghost.net/formmail.cgi" method="POST">
<input name="nome" type="text" class="nome" id="nome" required width="100%" placeholder="Nome:">
<input name="cpf" type="text" class="cpf" id="cpf" placeholder="CPF:">
<div style="clear:both"></div><br/>
<input name="nascimento" type="text" class="nascimento" id="nascimento" placeholder="Data de nascimento:">
<select id="chkveg">
<option value="https://pag.ae/7ULKPL7TH">Associados Ancord + C.Dados = R$700,00</option>
<option value="https://pag.ae/7ULKQ8Zm2">Associados Ancord = R$800,00</option>
<option value="https://pag.ae/7ULKQLB9m">Associados Entidades Apoiadoras + C.Dados = R$800,00</option>
</select>
<input id="btnget" class="submit-btn" type="submit" value="INSCREVER-SE">
</form>
For exemple:
IF (#FORM).REQUIRED = TRUE {
(#BUTTON).WINDOWOPEN
}
Thanks
Because you using a submit button you will need to return false, in case if you don't want to do anything. Before that, you need also to check if your required field are empty or not. (i.e. $(your field).val() === "" then it's empty, if all you need have, then call the window.open() function.
Note: you can merge multiple fields for checking ie: $(".your_field1, .your_field2, .your_field3").val() === "" however this is an OR operation.
One possible solution:
$(function() {
$('#btnget').click(function() {
let isEmpty = false;
$('#data_form input,textarea,select').filter(':visible').each(function(i) {
if ($(this).val() === "") {
isEmpty = true;
return false;
}
});
if (isEmpty) {
return false;
}
window.open($('#chkveg').val());
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="data_form" action="http://formmail.kinghost.net/formmail.cgi" method="POST">
<input name="nome" type="text" class="nome" id="nome" required width="100%" placeholder="Nome:">
<input name="cpf" type="text" class="cpf" id="cpf" placeholder="CPF:">
<div style="clear:both"></div><br/>
<input name="nascimento" type="text" class="nascimento" id="nascimento" placeholder="Data de nascimento:">
<select id="chkveg">
<option value="https://pag.ae/7ULKPL7TH">Associados Ancord + C.Dados = R$700,00</option>
<option value="https://pag.ae/7ULKQ8Zm2">Associados Ancord = R$800,00</option>
<option value="https://pag.ae/7ULKQLB9m">Associados Entidades Apoiadoras + C.Dados = R$800,00</option>
</select>
<input id="btnget" class="submit-btn" type="submit" value="INSCREVER-SE">
</form>
If you want only for the required fields, than use filter('[required]:visible') instead of filter(':visible').
I want to save state of selected checkbox to a file (whether as a text file or something else) that contains information on what was checked.
I can't use localstorage or cookies, I need it saved as external file so I can save (and load) several files with different checkmarks selected.
It's pretty straightforward, but I can't find any solution that does exactly this, so any help is appreciated.
Simple snippet for reference:
div {
display: table;
}
span {
display: block;
}
input,
label {
display: inline-block;
}
<div>
<span>
<input id="box1" type="checkbox" />
<label for="box1">Checkbox 1</label>
</span>
<span>
<input id="box2" type="checkbox" checked/>
<label for="box2">Checkbox 2</label>
</span>
<span>
<input id="box3" type="checkbox" />
<label for="box3">Checkbox 3</label>
</span>
</div>
<button id="_save">Save</button>
<button id="_load">Load</button>
Ok, I have a solution that does what I needed.
So when you check everything you want from your form, you can save it into localstorage and THEN you can export localstorage as JSON. I found this google extension that handles import and export for the localstorage (in a textual file), but you can always go extra mile and write your own script for that.
Here is JSFiddle for the localstorage so can save whatever input you want and here is chrome extension that handles import and export LocalStorage Manager.
Javascript:
;(function($) {
$.fn.toJSON = function() {
var $elements = {};
var $form = $(this);
$form.find('input, select, textarea').each(function(){
var name = $(this).attr('name')
var type = $(this).attr('type')
if(name){
var $value;
if(type == 'radio'){
$value = $('input[name='+name+']:checked', $form).val()
} else if(type == 'checkbox'){
$value = $(this).is(':checked')
} else {
$value = $(this).val()
}
$elements[$(this).attr('name')] = $value
}
});
return JSON.stringify( $elements )
};
$.fn.fromJSON = function(json_string) {
var $form = $(this)
var data = JSON.parse(json_string)
$.each(data, function(key, value) {
var $elem = $('[name="'+key+'"]', $form)
var type = $elem.first().attr('type')
if(type == 'radio'){
$('[name="'+key+'"][value="'+value+'"]').prop('checked', true)
} else if(type == 'checkbox' && (value == true || value == 'true')){
$('[name="'+key+'"]').prop('checked', true)
} else {
$elem.val(value)
}
})
};
}( jQuery ));
//
// DEMO CODE
//
$(document).ready(function(){
$("#_save").on('click', function(){
console.log("Saving form data...")
var data = $("form#myForm").toJSON()
console.log(data);
localStorage['form_data'] = data;
return false;
})
$("#_load").on('click', function(){
if(localStorage['form_data']){
console.log("Loading form data...")
console.log(JSON.parse(localStorage['form_data']))
$("form#myForm").fromJSON(localStorage['form_data'])
} else {
console.log("Error: Save some data first")
}
return false;
})
});
HTML:
<form action="#" method="get" id="myForm">
<input type="text" name="textfield">
Textfield
<br/>
<input type="number" name="numberfield" />
Numberfield
<br/>
<input type="radio" name="radiofield" value="1" />
<input type="radio" name="radiofield" value="2" />
<input type="radio" name="radiofield" value="3" />
Radiofields
<br/>
<input type="checkbox" name="checkfield">
<input type="checkbox" name="checkfield2">
<input type="checkbox" name="checkfield3">
Checkboxes
<br/>
<select name="selectbox">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Selectbox
<br/>
<textarea name="textarea"></textarea>
Textarea
<br/>
<hr/>
<button id="_save">Save</button>
<button id="_load">Load</button>
<input type="reset">
</form>
I've tried many different methods, and even tried searching on SO. No answer was what I was looking for.
What I want is to have two input buttons that do some things in pure javascript.
Button one: Have it say "Add" when the page loads. When clicked, the value changes to "Cancel." Also, when it's clicked, have it display a form with three fields. When it's clicked again, have the form disappear. One named 'name', the second named 'location', the third named 'type'. I want the user to be able to submit these three things and have them be stored in the code.
Button two: Take the user input from the form and each time the user clicks, it displays all three information values, but have the button act as random generator. Let's say the code has 5 separate entries, I want them to be randomly selected and displayed when the button is clicked.
Like I said, I tried to make this work, but couldn't quite get over the top of where I wanted to go with it. If you want to see my original code, just ask, but I doubt it will be of any assistance.
Thanks in advance.
EDIT: Added the code.
function GetValue() {
var myarray = [];
var random = myarray[Math.floor(Math.random() * myarray.length)];
document.getElementById("message").innerHTML = random;
}
var testObject = {
'name': BWW,
'location': "Sesame Street",
'type': Bar
};
localStorage.setItem('testObject', JSON.stringify(testObject));
var retrievedObject = localStorage.getItem('testObject');
function change() {
var elem = document.getElementById("btnAdd1");
if (elem.value == "Add Spot") {
elem.value = "Cancel";
} else elem.value = "Add Spot";
}
window.onload = function() {
var button = document.getElementById('btnAdd1');
button.onclick = function show() {
var div = document.getElementById('order');
if (div.style.display !== 'none') {
div.style.display = 'none';
} else {
div.style.display = 'block';
}
};
};
<section>
<input type="button" id="btnChoose" value="Random Spot" onclick="GetValue();" />
<p id="message"></p>
<input type="button" id="btnAdd1" value="Add Spot" onclick="change();" />
<div class="form"></div>
<form id="order" style="display:none;">
<input type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" />
<input type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" />
<input type="text" name="location" placeholder="Location" required="required" autocomplete="off" />
<input type="submit" value="Add Spot" />
</form>
</div>
</section>
The randomizer works, and so does the appear/hide form. Only thing is storing the input and switching the input value.
Here's one way to do this. Each form submission is stored as an object in an array. The random button randomly selects an item from the array and displays it below.
HTML:
<section>
<input type="button" id="btnChoose" value="Random Spot" />
<p id="message"></p>
<input type="button" id="btnAdd1" value="Add Spot" />
<div class="form">
<form id="order" style="display:none;">
<input id="orderName" type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" />
<input id="orderType" type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" />
<input id="orderLocation" type="text" name="location" placeholder="Location" required="required" autocomplete="off" />
<input type="submit" value="Add Spot" />
</form>
</div>
</section>
<div id="randomName"></div>
<div id="randomLocation"></div>
<div id="randomType"></div>
JS:
var formData = [];
var formSubmission = function(name, location, type) {
this.name = name;
this.location = location;
this.type = type;
}
var spotName = document.getElementById("orderName"),
spotLocation = document.getElementById("orderLocation"),
spotType = document.getElementById("orderType");
var addClick = function() {
if (this.value === 'Add Spot') {
this.value = "Cancel";
document.getElementById('order').style.display = 'block';
}
else {
this.value = 'Add Spot';
document.getElementById('order').style.display = 'none';
}
}
document.getElementById("btnAdd1").onclick = addClick;
document.getElementById('order').onsubmit = function(e) {
e.preventDefault();
var submission = new formSubmission(spotName.value, spotLocation.value, spotType.value);
formData.push(submission);
submission = '';
document.getElementById('btnAdd1').value = 'Add Spot';
document.getElementById('order').style.display = 'none';
this.reset();
}
var randomValue;
document.getElementById('btnChoose').onclick = function() {
randomValue = formData[Math.floor(Math.random()*formData.length)];
document.getElementById('randomName').innerHTML = randomValue.name;
document.getElementById('randomLocation').innerHTML = randomValue.location;
document.getElementById('randomType').innerHTML = randomValue.type;
}
I was working on something since you first posted, and here is my take on it:
HTML:
<section>
<p id="message">
<div id="name"></div>
<div id="location"></div>
<div id="type"></div>
</p>
<input type="button" id="btnAdd" value="Add" onclick="doAdd(this);" />
<input type="button" id="btnShow" value="Show" onclick="doShow(this);" />
<div class="form">
<script id="myRowTemplate" type="text/template">
<input type="text" name="name" placeholder="Name of Resturant" required="required" autocomplete="on" onchange="onChanged(this, {{i}})" />
<input type="text" name="type" placeholder="Type of Food" required="required" autocomplete="off" onchange="onChanged(this, {{i}})" />
<input type="text" name="location" placeholder="Location" required="required" autocomplete="off" onchange="onChanged(this, {{i}})" />
</script>
<form id="order" style="display:none;">
<div id="formItems">
</div>
<input type="button" value="Add Spot" onclick="addSpot()" />
</form>
</div>
</section>
JS:
function GetValue() {
if (enteredItems.length) {
var entry = enteredItems[Math.floor(Math.random() * enteredItems.length)];
document.getElementById("name").innerHTML = entry.name;
document.getElementById("location").innerHTML = entry.location;
document.getElementById("type").innerHTML = entry.type;
}
}
function doAdd(elem) {
switch (elem.value) {
case "Add":
document.getElementById('order').style.display = "";
elem.value = "Cancel";
break;
case "Cancel":
document.getElementById('order').style.display = "none";
elem.value = "Add";
break;
}
}
function doShow(elem) {
GetValue();
}
function addSpot(index) { // (note: here, index is only for loading for the first time)
if (index == undefined) index = enteredItems.length;
var newRowDiv = document.createElement("div");
newRowDiv.innerHTML = document.getElementById("myRowTemplate").innerHTML.replace(/{{i}}/g, index); // (this updates the template with the entry in the array it belongs)
if (enteredItems[index] == undefined)
enteredItems[index] = { name: "", location: "", type: "" }; // (create new entry)
else {debugger;
newRowDiv.children[0].value = enteredItems[index].name;
newRowDiv.children[1].value = enteredItems[index].location;
newRowDiv.children[2].value = enteredItems[index].type;
}
document.getElementById("formItems").appendChild(newRowDiv);
}
function onChanged(elem, index) {
enteredItems[index][elem.name] = elem.value;
localStorage.setItem('enteredItems', JSON.stringify(enteredItems)); // (save each time
}
// update the UI with any saved items
var enteredItems = [];
window.addEventListener("load", function() {
var retrievedObject = localStorage.getItem('enteredItems');
if (retrievedObject)
enteredItems = retrievedObject = JSON.parse(retrievedObject);
for (var i = 0; i < enteredItems.length; ++i)
addSpot(i);
});
https://jsfiddle.net/k1vp8dqn/
It took me a bit longer because I noticed you were trying to save the items, so I whipped up something that you can play with to suit your needs.
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);
}
});
}