I was wondering how is it popssible to populate forms using JSON?
I have a JSON string which I get using php's json_encode()
And I want to use the JSON string to populate form controls (such as textarea or text input).
How can I achieve such thing without using external plugins (like jQuery populate plugin, which I saw).
EDIT: JSON format:
[{"id":"41","parent_id":null,"node_name":"name","slug":"","lft":"3","rgt":"4"}]
This is what I get from json_encode()
Formating data to JSON and making a POST request fromEntries() method. Using the JSON. stringify() method then format the plain form data as JSON. Specify the HTTP request method as POST and using the header field of the Fetch API specify that you are sending a JSON body request and accepting JSON responses back.
JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax.
There is a problem here with textarea
, then I change it to a default
switch value
Use this to assign values to Many Controls :
function populate(frm, data) { $.each(data, function(key, value) { var ctrl = $('[name='+key+']', frm); switch(ctrl.prop("type")) { case "radio": case "checkbox": ctrl.each(function() { if($(this).attr('value') == value) $(this).attr("checked",value); }); break; default: ctrl.val(value); } }); }
For just text controls (i.e. no radios or checkboxes), you can make a simple version of a populate function:
function populate(frm, data) { $.each(data, function(key, value){ $('[name='+key+']', frm).val(value); }); }
Usage example:
populate('#MyForm', $.parseJSON(data));
Demo: http://jsfiddle.net/Guffa/65QB3/3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With