user1176783
user1176783

Reputation: 673

jQuery prepopulate and format a text field

This is confusing me.

I have a PHP app with a text field, the client wants the field to be prepopulated with 896- and followed by user input of only five numeric values, so it would be like 896-12569. I

I would like to do this in jQuery, is this possible, if so how?

Upvotes: 0

Views: 234

Answers (2)

billyonecan
billyonecan

Reputation: 20250

I'd suggest doing this using CSS, but here is a jQuery solution:

$('input').on('keyup', function() {
  var prefix = '896-';
  var value = this.value.replace(prefix, '').replace(/[^\d]/, '').substr(0, 5);
  this.value = prefix + value;
}).keyup(); // trigger the keyup event, so that the field is populated at load

Obviously swap input for the relevant selector, and add events as necessary (this example only works on the keyup event).


Edit

Having looked at the code again, I noticed there's a small bug (press backspace once), ths prefix gets added again (this is because it isn't removed from the input because it no longer matches), a quick fix would be to just always replace the first 4 characters of the input:

var value = this.value.replace(this.value.substr(0, 4), '').replace(/[^\d]/, '').substr(0, 5);

Upvotes: 2

Alec Gorge
Alec Gorge

Reputation: 17390

You don't need jQuery for this.

Simply put the 896- outside the input field and style it to look normal

<div class="controls">
    896-<input type="text" name="postfix" class="prefixed-input" />
</div>

Then, in PHP you can prefix the 896- to the number before you store it.

See an example on Bootstraps website. Under the "Extending form controls" heading.

Upvotes: 0

Related Questions