Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

html - Disable Text Entry in <input type="number">

I am making a simple web app. At one part of it, I have included an input box of type="number"

<input type="number" min="0">

Anyhow, when I run the code in my latest Google Chrome Browser, I am able to enter text too:

I entered text in an input type of number

I do not want users to be able to do that. How should I rectify this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use JavaScript (e.g. with jQuery) to allow only specific characters:

// Catch all events related to changes
$('#textbox').on('change keyup', function() {
  // Remove invalid characters
  var sanitized = $(this).val().replace(/[^0-9]/g, '');
  // Update value
  $(this).val(sanitized);
});

Here is a fiddle.

Same thing with support for floats:

// Catch all events related to changes
$('#textbox').on('change keyup', function() {
  // Remove invalid characters
  var sanitized = $(this).val().replace(/[^0-9.]/g, '');
  // Remove the first point if there is more than one
  sanitized = sanitized.replace(/.(?=.*.)/, '');
  // Update value
  $(this).val(sanitized);
});

And here is another fiddle.

Update: Although you might not need this, here is a solution that allows a leading minus sign.

// Catch all events related to changes
$('#textbox').on('change keyup', function() {
  // Remove invalid characters
  var sanitized = $(this).val().replace(/[^-0-9]/g, '');
  // Remove non-leading minus signs
  sanitized = sanitized.replace(/(.)-+/g, '$1');
  // Update value
  $(this).val(sanitized);
});

3rd fiddle

And now a final solution that allows only valid decimals (including floats and negative numbers):

// Catch all events related to changes
$('#textbox').on('change keyup', function() {
  // Remove invalid characters
  var sanitized = $(this).val().replace(/[^-.0-9]/g, '');
  // Remove non-leading minus signs
  sanitized = sanitized.replace(/(.)-+/g, '$1');
  // Remove the first point if there is more than one
  sanitized = sanitized.replace(/.(?=.*.)/g, '');
  // Update value
  $(this).val(sanitized);
});

Final fiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...