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>

2
  • So did you attempt anything? Commented Aug 3, 2021 at 19:32
  • Why? Because you replace the value and the browser sets the focus to the end. Commented Aug 3, 2021 at 19:33

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

4 Comments

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?
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;
Honestly, I don't know, this may help you stackoverflow.com/questions/512528/…
I am following this post, stackoverflow.com/questions/8219639/… But not able to understand it properly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.