使用jquery的TextBox按键

时间:2014-02-22 07:23:39

标签: jquery

(我使用的是html + J-query) 我有一个情况,我有一个文本框,和 每当用户第一次在其中键入任何内容时,该字符必须附加@符号,并且键入的下一个字符必须放在@符号之前。

代表。 第一个字符键入: C@ 第二个字符键入: CF @

这是我到目前为止所尝试的,

    '<script> 
        $(document).ready(function(){               
       var v=$('#title').val();
         if(!v)
             {
                $('#title').on('key up', function(){
                this.value = this.value+'@';
                });
             }
         else
           var s=this.value;
           var x=s.replace(s. sub string (s.length-1, s.length),'@' );
     });
    </script>
    </head>
    <body>
    <input type="text" id="title" value=""/>
    </body>`

2 个答案:

答案 0 :(得分:1)

这就是我开始工作的方式

http://jsfiddle.net/DmV8e/

HTML

<input type="text" id="title" value="" />

Javascript

$(document).ready(function () {
    var titleValue = null;                  //Create a variable to store the value
    $('#title').keyup(function () {         //properly bind the keyup function
        if (titleValue == null) {           //check to see if the stored value is null
            this.value = this.value + '@';  //append the @ symbol to the end of the value
            this.setSelectionRange(1, 1);   //basically set the cursor's index to 1
            titleValue = this.value;        //store the new value
        } else if (this.value == "") {      //if the value was not null, check to see if the textbox is empty
            titleValue = null;              //reset the variable to null so the first if will trip on keyup
        }
    });
});

答案 1 :(得分:1)

请查看以下代码,它将满足您的目的:

HTML:

<input type="text" id="txtDemo" />

Jquery的:

$(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] + '@')
        }
    }
 })
})
相关问题