1

I have checkbox and input text and I need turn input charaters to uppercase, only when checkbox is checked.

So, if checkbox is not checked and and I type "aa", then check checkbox and type "bb", result should be: "aaBB"

I have this code but this is incorrect, as it turns entire input value to uppercase, when checkbox is checked.

$(document).ready(function() {
  $('input').keyup(function() {
    if ($("#ch").is(":checked")) {
      this.value = this.value.toLocaleUpperCase();
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="ch" />
<input type="text" id="myinp" />

http://jsfiddle.net/tqa8p9ub/

Sivaramakrishnan
  • 689
  • 1
  • 4
  • 11
Oto Shavadze
  • 40,603
  • 55
  • 152
  • 236

2 Answers2

3

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" />
jo_va
  • 13,504
  • 3
  • 23
  • 47
0

Try this -

$(document).ready(function() {
    $('input').keyup(function(e) {
        if ($("#ch").is(":checked")) {
          let lastChar = e.key;
          lastChar = lastChar.toUpperCase();
          this.value = this.value.substr(0, this.value.length - 1) + lastChar;
        }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="ch" />
<input type="text" id="myinp" />

Live in action - https://jsitor.com/Q0aigCO1j

FZs
  • 16,581
  • 13
  • 41
  • 50
Ashvin777
  • 1,446
  • 13
  • 19