0

I have an input field in my code: <input type=text name=code id=code>.

What I want to do is to convert a specific text to another one as the user types in the field.

Let me explain more. When the user enters 31546 in the input, I want that text to directly convert to HELLO.

I know this can be done using JavaScript/jQuery, but I can't have any ideas on how to achieve this. How can I?

P.S. If it's easier to work with a textarea, I'm ready to change my input to a textarea.

EDIT: I got a code from this StackOverflow post which detects any changes to an element,

 $('.myElements').each(function() {
   var elem = $(this);

   // Save current value of element
   elem.data('oldVal', elem.val());

   // Look for changes in the value
   elem.bind("propertychange change click keyup input paste", function(event){
      // If value has changed...
      if (elem.data('oldVal') != elem.val()) {
       // Updated stored value
       elem.data('oldVal', elem.val());

       // Do action
       ....
     }
   });
 });

but I am not sure how to utilise this for what I want.

Please bear with me as I am yet a fledgling in this domain.

Thank you.

Community
  • 1
  • 1
Veo
  • 291
  • 3
  • 14

3 Answers3

1

One option is to set up a keyup event for your input and then replace the value as the user types. For example:

$('input').keyup(function () {
    var val = $(this).val();

    var newVal = val.split('31546').join('HELLO');

    if (newVal !== val) {
        $(this).val(newVal);
    }
});
Paul Nispel
  • 731
  • 6
  • 10
0

You can use keyup event as,

$(document).on('keyup', '#code', function() {
  $('#code').val(convertedValue($('#takeInput').val()));
})

function convertedValue(val) {
  return 'hello';
}
syms
  • 413
  • 2
  • 12
  • Thanks for your answer. The code you provided changes the input's data to `hello` on any keypress in the inputfield. – Veo Jul 01 '15 at 05:18
  • yeah right you can put there your converted values as you want as per input. – syms Jul 01 '15 at 11:03
0

This may help you :--

   <input type="text" id="code">

    $('#code').bind('change click keyup onpaste', function(ele){
        var origVal = ele.target.value;
        if(origVal.indexOf("123") !== -1){
            ele.target.value = origVal.replace("123","Hello");
        }
    });
Shekhar Khairnar
  • 2,643
  • 3
  • 26
  • 44