Reputation: 13
(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. 1st char typed: c@ 2nd char typed: cf@
This is what I have tried so far,
'<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>`
Upvotes: 1
Views: 131
Reputation:
Kindly look into the below code it will serve your purpose:
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] + '@')
}
}
})
})
Upvotes: 1
Reputation: 2869
This is how I just got it to work
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
}
});
});
Upvotes: 1