Dynamically fill in form values with jQuery Dynamically fill in form values with jQuery database database

Dynamically fill in form values with jQuery


Assuming this example HTML:

<input type="text" name="email" id="email" /><input type="text" name="first_name" id="first_name" /><input type="text" name="last_name" id="last_name" />

You could have this javascript:

$("#email").bind("change", function(e){  $.getJSON("http://yourwebsite.com/lokup.php?email=" + $("#email").val(),        function(data){          $.each(data, function(i,item){            if (item.field == "first_name") {              $("#first_name").val(item.value);            } else if (item.field == "last_name") {              $("#last_name").val(item.value);            }          });        });});

Then just you have a PHP script (in this case lookup.php) that takes an email in the query string and returns a JSON formatted array back with the values you want to access. This is the part that actually hits the database to look up the values:

<?php//look up the record based on email and get the firstname and lastname...//build the JSON array for return$json = array(array('field' => 'first_name',                     'value' => $firstName),               array('field' => 'last_name',                     'value' => $last_name));echo json_encode($json );?>

You'll want to do other things like sanitize the email input, etc, but should get you going in the right direction.


Automatically fill all form fields from an array

http://jsfiddle.net/brynner/wf0rk7tz/2/

JS

function fill(a){    for(var k in a){        $('[name="'+k+'"]').val(a[k]);    }}array_example = {"God":"Jesus","Holy":"Spirit"};fill(array_example);

HTML

<form><input name="God"><input name="Holy"></form>


If you need to hit the database, you need to hit the web server again (for the most part).

What you can do is use AJAX, which makes a request to another script on your site to retrieve data, gets the data, and then updates the input fields you want.

AJAX calls can be made in jquery with the $.ajax() function call, so this will happen

User's browser enters input that fires a trigger that makes an AJAX call

$('input .callAjax').bind('change', function() {   $.ajax({ url: 'script/ajax',            type: json           data: $foo,             success: function(data) {             $('input .targetAjax').val(data.newValue);           });  );

Now you will need to point that AJAX call at script (sounds like you're working PHP) that will do the query you want and send back data.

You will probably want to use the JSON object call so you can pass back a javascript object, that will be easier to use than return XML etc.

The php function json_encode($phpobj); will be useful.