Capitalise the first letter of every word as user types unless user insists on lower case

Viewed 110

I am working on the script where I want the first letter and the letter after a space to be capitalized. If a word follows a hyphen (-), it should not be capitalized until and unless a space follows after the hyphen (-). If the user wants to lower case the first letter of any word, it should work dynamically.

This I achieved using the below script.

The challenge here is, that it should be possible for the user to change the uppercased letter to a lower case while typing

I am not able to achieve that feature.

Example:

If the user types "hello world", the output will be "Hello World", and if the user wants to lower case the letter "W" from the word "World" by deleting the letter "W" and retyping the letter "w", the expected result should be "Hello world".

$.fn.capitalize = function() {
  $.each(this, function() {
    var split = this.value.split(' ');
    for (var i = 0, len = split.length; i < len; i++) {
      split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
    }
    this.value = split.join(' ');
  });
  return this;
};

$('textarea').on('keyup', function() {
  $(this).capitalize();
}).capitalize();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<textarea></textarea>

3 Answers
Related