TextBox keypress using jquery

(I m using html + J-query ) I have a situation in which I have a Text box ,and whenever the user types anything in it for the first time the character must be appended with @ symbol, and the next characters typed must be placed just before the @ symbol.

for ex.
when
1st char typed ‘c’ : c@
2nd char typed ‘f’ : cf@
3rd char typed ‘d’ : cfd@
This is what I have tried so far,

$(document).ready(function () {    
    $('#txtDemo').keyup(function () {
    if ($(this).val().trim().length == 1) {
        if ($(this).val().indexOf('@') === -1) {
            $(this).val($(this).val() + '@');
        }
        else {
            $(this).val('')
        }
    }
    else {
        if ($(this).val().indexOf('@') === -1) {
            $(this).val($(this).val() + '@');
        }
        else {
            var jam = $(this).val().split('@');
            $(this).val(jam[0] + jam[1] + '@')
        }
    }
 })
})

Hi there,

Welcome to the forums :slight_smile:

You can do it like this:

function setCaretPosition(elemId, caretPos) {
    var el = document.getElementById(elemId);

    el.value = el.value;
    // ^ this is used to not only get "focus", but
    // to make sure we don't have it everything -selected-
    // (it causes an issue in chrome, and having it doesn't hurt any other browser)

    if (el !== null) {

        if (el.createTextRange) {
            var range = el.createTextRange();
            range.move('character', caretPos);
            range.select();
            return true;
        }

        else {
            // (el.selectionStart === 0 added for Firefox bug)
            if (el.selectionStart || el.selectionStart === 0) {
                el.focus();
                el.setSelectionRange(caretPos, caretPos);
                return true;
            }

            else  { // fail city, fortunately this never happens (as far as I've tested) :)
                el.focus();
                return false;
            }
        }
    }
}

$("#myBox").on("keyup", function(){
    var val = this.value;
    if(!val.match(/@$/) && val.length>0){
        this.value = val + "@"
    }  
    setCaretPosition("myBox", this.value.length -1);
});

Here’s a demo.

I got the function to set the cursor position here: http://stackoverflow.com/questions/512528/set-cursor-position-in-html-textbox#answer-12518737

HTH