Matt Matt - 8 days ago 6
jQuery Question

How to set text in textbox jquery

I know to get the value of text box is like

$("#text").val();
<input type="text" id="text" />


But I want to enter
-
after a few numbers like if I enter 021 (three numbers) it should put - after it like
021-
012-
it.

This is what I have done.

$(document).ready(function(){
$("#text").on('focus',function()
{
if((this).val() == "021"){
$("#text").text('-');
}
}
}


But this method isn't working neither I believe it is on right way. Can anyone do it?

Answer

What you enter inside an input element is only the value and isn't the HTML or .text() of the element. Instead keep using .val() and do:

$("#text").val($("#text").val()+"-");

Mention of this is noted in the jQuery documentation for .text():

The .text() method cannot be used on form inputs or scripts. To set or get the text value of input or textarea elements, use the .val() method.