Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery and JSON to populate forms?

Tags:

json

jquery

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()

like image 444
Itai Sagi Avatar asked Sep 04 '11 09:09

Itai Sagi


People also ask

Can we send JSON in form data?

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.

What is JSON full form?

JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax.


2 Answers

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);          }       });   } 
like image 125
Nowshath Avatar answered Sep 24 '22 16:09

Nowshath


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/

like image 37
Guffa Avatar answered Sep 20 '22 16:09

Guffa