0

I am using jQuery, when numeric values enter in inputbox e.g. 1234 it converts those into ABCD respectively. But I want to convert this jQuery function into pure Javascript. Please take a look at my jQuery code that is working perfectly fine and suggest how can I convert it into Javascript (I am also confused why it is always taking me at the last typed alphabet, if I type in the middle?).

$(document).ready(function(){
  $('input[name="xrd-reference"]').bind("change keyup input",function() {
    $('input[name="xrd-reference"]').val($('input[name="xrd-reference"]').val().replace(/1/g, 'A').replace(/2/g, 'B').replace(/3/g, 'C').replace(/4/g, 'D').replace(/5/g, 'E').replace(/6/g, 'F').replace(/7/g, 'G').replace(/8/g, 'H').replace(/9/g, 'I').replace(/0/g, 'O')); 
  });
});
<input name='xrd-reference'>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Tewatia
  • 13
  • 3

1 Answers1

1

It will be something like this

<input name="xrd-reference">

<script>
    const substitutions = {
        1: 'A',
        2: 'B',
        3: 'C',
        4: 'D',
        5: 'E',
        6: 'F',
        7: 'G',
        8: 'H',
        9: 'I',
        0: 'O'
    };
    window.onload = () => {
        const input = document.querySelector('[name=xrd-reference]');
        input && input.addEventListener('input', e => {
        input.value = input.value.replace(/[0-9]/g, (char) => substitutions[char] || char);
        });
    }

    
</script>
Flash
  • 1,101
  • 1
  • 9
  • 13
  • Thank you so much for your answer sir, it really helped me understanding Javascript more deeply. Can you please also tell me why the cursor always goes to last when I am typing in some middle and how can keep it where I am typing? – Tewatia Aug 03 '21 at 19:34
  • I have search over internet and I found that we can store cursor position in variable and then set cursor position again. But It is not working, I don't know why? let position = document.querySelector('[name=xrd-reference]').getCursorPosition(); document.querySelector('[name=xrd-reference]').setCursorPosition() = position; – Tewatia Aug 03 '21 at 19:45
  • Honestly, I don't know, this may help you https://stackoverflow.com/questions/512528/set-keyboard-caret-position-in-html-textbox – Flash Aug 03 '21 at 19:57
  • I am following this post, https://stackoverflow.com/questions/8219639/stop-cursor-from-jumping-to-end-of-input-field-in-javascript-replace But not able to understand it properly. – Tewatia Aug 03 '21 at 20:03