0

I have an application with an Input field which needs to be converted to Uppercase as soon as the User enters a character. This is working as expected.

But if the user tries to enter a character between an already existing word, the cursor is pushed to the end of the Input field. Is there a way I can keep the cursor in the proper location?

Before you down vote, I did check out posts in Stack Overflow and other places. Couldn't find a proper solution. Do provide your feedback.

JSFiddle Link

$(function() {
  $("#referenceNo").on('keyup change', function(e) {
    $(this).val($(this).val().toUpperCase());
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="referenceNo">Reference No</label>
<br/>
<input type="text" id="referenceNo" name="referenceNo" value="HELLO WORLD!" />

Try to input a character between "Hello World!", the cursor will be pushed to the end of the word. This needs fixing..

3 Answers 3

2

Try this, You can use setSelectionRange Working Fiddle

$(function () {
    $("#referenceNo").on('keyup change', function (e) {            
        var startPos = this.selectionStart,
        endPos = this.selectionEnd;    

        $(this).val($(this).val().toUpperCase());    
        // restore cursor
        this.setSelectionRange(startPos, endPos );

    });
});

Also you can use pure CSS

   #referenceNo {
     text-transform: uppercase
   }
Sign up to request clarification or add additional context in comments.

2 Comments

The css solution is nice! Where did you found it?
Tried this, it works. Will be using this code for now. Thanks. Will keep the question open for a day or so to see if a better answer turns up.
2

I suggest you to do this by CSS. Add text-transform property to the element:

#referenceNo {
    text-transform: uppercase
}

No script needed.

Fiddle

1 Comment

In the JS code, I still am getting small characters. This is a neat trick, did see it in one of the other question but not useful in my case. Thanks for the suggestion.
1

You Can Achieve visualization by CSS and for value sending to server you can use javascript.

Like: this is CSS Code

#abc {
    text-transform: uppercase
}

this is HTML:

<input class="form-control" type="text" id="abc" />

this is javascript:

$("#abc").on("change", function(){ var x = $("#abc").val().toUpperCase(); });

you can use "keyup" event for instant value if you have not required then you don't have need to bind extra event with your code.

2 Comments

Thanks, Appreciate the simpler solution.
Yup, just did. Was away for the weekend, so the delay.

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.