Home > Mobile >  Changing input values on keyup by class name
Changing input values on keyup by class name

Time:12-13

I'm attempting to adapt an existing Jquery script which corrects the case on input values as they are being typed - previously it has run by me manually adding an onkeyup event to the input to call the script but I'd like it run based on classname instead.

I attempted to adapt the guidance given at keyup events using class instead of id so that my script will run when the element has a class of "correctcase" but so far haven't had success in getting the script to update the value but I'm not clear on what I'm missing.

Currently I have:

(function($) {

    $('.correctcase').keyup(function(event){
       
        return $(this).val().replace(
            /\w\S*/g,
            function(txt) {
                return txt.charAt(0).toUpperCase()   txt.substr(1).toLowerCase();
            }
        );

    });

})( jQuery );

The previous onkeyup attribute added to the element was:

onkeyup="this.value=toTitleCase(this.value)"

So I'm sure I'm just missing something in terms of passing the value properly?

CodePudding user response:

Inside your event handler you were returning the transformed value instead you needed to use it to set the value of the input element.

$('.correctcase').keyup(function(event){       
  const currentValue = $(this).val();
  const transformed =
        currentValue.replace(/\w\S*/g,
          function(txt) {                
            return txt.charAt(0).toUpperCase()   txt.substr(1).toLowerCase();
          }
        );
  $(this).val(transformed);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text"  value="">

  • Related