Question

I know this is possible in javascript by using window.getSelection() method but I'm not familiar with this selection object. Can you help me to write a code to make user's writing cursor to be always at the begining of the input string?

$('input[type="text"]')
    .attr('maxlength','7')
    .keyup(function(){
        var sel = window.getSelection();
        console.log(sel);
        // need a code for here to make the cursor (caret) at the begining of the string

    })
Was it helpful?

Solution

Can be done using a combo of:

  • dir = "rtl"
  • moving text box caret to 0 after every keypress

Demo: http://jsfiddle.net/FF9Tf/1/

Note: Uses hints/code from these answers.

OTHER TIPS

you could always use CSS direction: rtl; this line of code simply changes the direction of the text to Right To Left and then u could just add the css class to your html elements using .addClass("your_class")

It's important to note that this method does not replace a class. It simply adds the class, appending it to any which may already be assigned to the elements.

Edit: Try putting .addClass("your_class") outside the keyup function (although that might still not give you the best result you are looking for), check my comment below for a better way to do it.

Update: here is another way to do it

$('input[type="text"]').change(function () {
$(this).val() = $(this).split("").reverse().join("");
});

try this, it will keep the cursor blinking at the beginning of the text in the input box

$('input[type="text"]')
    .attr('maxlength','7')
    .attr('dir', "rtl")
    .keyup(function(){
        var sel = window.getSelection();
        console.log(sel);
        // need a code for here to make the cursor (caret) at the begining of the string

    })

try the demo link http://jsfiddle.net/hcWCQ/1/

in the eg: click on the input box and then press Shift+TAB and then start typing not exactly what u r looking for.... but somewhere close

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top