user7219632
user7219632

Reputation:

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?

Upvotes: 1

Views: 1130

Answers (2)

Sam Jacob
Sam Jacob

Reputation: 1

$('#text').keyup(function() {
    var val = this.value.replace(/\D/g, '');
    var newVal = '';
    while (val.length > 3) {
        newVal += val.substr(0, 3) + '-';
        val = val.substr(3);
    }
    newVal += val;`enter code here`
    this.value = newVal;
});

http://jsfiddle.net/ssthil/nY2QT/

Upvotes: 0

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21565

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.

Upvotes: 3

Related Questions