Wahtever
Wahtever

Reputation: 3678

how to add a character into a textbox

i would like to add a character to a text-box that separates two characters from two like this :

22:11

so when the user enters 22 it auto switch to after the separator and then the user can enter 11.

how can i do this , thanks.

Upvotes: 0

Views: 1167

Answers (4)

Teneff
Teneff

Reputation: 32158

You could do it like this:

$('#textbox').keyup(function(){
  if ($(this).val().length == 2) {
    $(this).val( $(this).val() + ':');
  }
});

just keep in mind that this example uses .keyup() method which is invoked when the user releases the button so if he releases the button when the value is 222 it won't work

edit:

and this is an improved example using regex:

$('#textbox').keyup(function(){
    t = $(this);
    v = t.val();
    pattern = /^(\d{2})(\d*)$/;
    if (v.match(pattern)) {
        t.val(v.replace(pattern, '$1:$2'));
    }
});

jsFiddle

Upvotes: 1

Andrea Colleoni
Andrea Colleoni

Reputation: 6021

  • Bind keyUp event of textbox
  • in the triggered function check for a RegExp (e.g. [0-2][0-9])
  • if match add to val() the ':' string

Upvotes: 0

Bala R
Bala R

Reputation: 108957

You can could using the Masked Input plugin with pattern "99:99"

JsFiddle link

For asp.net, if you are using ASP.NET AJAX Control Toolkit, you can use the MaskedEdit extension.

Upvotes: 0

stekkie
stekkie

Reputation: 53

Use the 'MaskedEdit' control instead of a textbox. Use '99:99' as the mask.

More info here: http://www.asp.net/ajaxlibrary/HOW%20TO%20Use%20the%20MaskedEdit%20Control.ashx

Upvotes: 1

Related Questions