You can do this with plain JavaScript using the keypress
event and adding the character uppercased or not to the current input value depending on your checkbox state.
Using the keypress
event is preferable to using keyup
since you can intercept the key before it gets added to the input, which allows you to transform it or not or even discard it. Using keyup
however forces you to change the whole input value since the value will already have been added to the input. You may also see a small flicker in this case.
Also you have to prevent the event from finishing executing by calling event.preventDefault()
, otherwise the character will be added twice to the input.
You also need to insert the character at the right position using input.selectionStart
. Once inserted, you have to increment both input.selectionStart
and input.selectionEnd
, see this answer for more details.
const checkbox = document.querySelector('#ch');
const input = document.querySelector('#myinp');
input.addEventListener('keypress', event => {
const checked = checkbox.checked;
const char = checkbox.checked ? event.key.toLocaleUpperCase() : event.key;
const pos = input.selectionStart || 0;
input.value = input.value.slice(0, pos) + char + input.value.slice(pos);
input.selectionStart = pos + 1;
input.selectionEnd = pos + 1;
event.preventDefault();
});
<input type="checkbox" id="ch" />
<input type="text" id="myinp" />