0

Global Json object which is initialized through ajax post call to php and it returns values like following(

$arr = array('h' => 'html', 'l' => 'li', 'p' => 'pre', 'd' =>'dom', 'e' => 'element'); 
echo json_encode($arr);

I can get the value of json object in jQuery.

There is a textbox to which ketpress event is mapped. Is it possible where user type the letter h in textbox instead of h it should replaced with value json_obj['h'] that is html. Where json_obj is variable which hold the json object.

kiranking
  • 306
  • 11
  • 29

3 Answers3

1

A lot of questions in here: final example

json_encode the php array: echo json_encode($arr);

jquery ajax

 var lookUpObject;
 $.getJSON({
     'something.php',
      success: function (data) {
         lookUpObject = data;
      }
 });

then keypress

var lookUpObject = { h: 'html', p: 'php' };

$(document).ready(function() {
    $('input').keypress(function (event) {
        var result = lookUpObject [String.fromCharCode(event.which)];

        if (result) {
            var val = $(this).val();
            $(this).val(val + result);
            event.preventDefault();
        }
    })
});
Joe
  • 80,724
  • 18
  • 127
  • 145
0

This will capture keyup events and use the key pressed to replace the textbox's text with what is in your array. Notice though I did not put in any validation or error checking (such as if key pressed exists in array) which you should probably do.

$('#inputID').keyup(function(e) {
  var key = String.fromCharCode(e.which);
  $(this).val($arr[key]);
});
Chad
  • 19,219
  • 4
  • 50
  • 73
0

First of all check, does item user pressd is in array. If so, then prevent default action and put that value.

Community
  • 1
  • 1
Ernestas Stankevičius
  • 2,420
  • 2
  • 24
  • 30