0

My jsp page has a select box with all userIds. And I have two text boxes for username and Data of birth. I want to autofill the textboxes when I select a userid from dropdown list.

I have a separate Servlet class and Database class for querying.

How to automatically the textboxes when I select userid from dropdown ? And i want this textboxes to be not editable. Can someone provide me example code.

1 Answers1

0

This JS Fiddle showing how to implement it:

var $select = document.getElementById('slct'),
    $un = document.getElementById('un'),
    $dob = document.getElementById('dob'),
    val, arr, username, dob;

// usually this array is obtained from a server response 
arr = [
     usr1 = ['user1', 'dob1'],
     usr2 = ['user2', 'dob2'],
     usr3 = ['user3', 'dob3'],
     usr4 = ['user4', 'dob4']
    ];

$select.addEventListener('change', function(){
 val = this.value - 1; // because arrays start at 0.
 username = arr[val][0];
    dob = arr[val][1];
    $un.value = username;
    $dob.value = dob;
});
<select id="slct">
    <option></option>
    <option value="1">id 1</option>
    <option value="2">id 2</option>
    <option value="3">id 3</option>
    <option value="4">id 4</option>
</select>
<input type="text" id="un" disabled>
<input type="text" id="dob" disabled>
Mi-Creativity
  • 9,554
  • 10
  • 38
  • 47
  • Thanks. How to construct the array from the servlet response rather than hardcoded array. I guess it should be a two dimensional array with userId = [username,DOB] – user1852324 Nov 22 '15 at 09:05
  • Well you can use AJAX to get result back as a2 dimensional array or as JSON response, I work with php not jsp but it's the same idea I will give you some examples. – Mi-Creativity Nov 22 '15 at 21:48
  • just used google search and i got these: https://www.youtube.com/watch?v=4VgHJCAKZZQ :: https://www.youtube.com/watch?v=V2jyMzSfVLE :: http://stackoverflow.com/questions/9046331/creating-a-json-object-in-jsp-and-using-it-with-jquery – Mi-Creativity Nov 22 '15 at 21:50
  • http://stackoverflow.com/questions/9124960/how-to-simply-return-json-from-a-jsp :: http://www.programming-free.com/2012/09/ajax-with-servlets-using-jquery-and-json.html :: http://www.simplecodestuffs.com/ajax-implementation-in-jsp-servlet-using-jquery-and-json/ – Mi-Creativity Nov 22 '15 at 21:55