MrNew
MrNew

Reputation: 1414

How to allow input number type to have space and comma

How can you allow input type="number" to accept something like 1, 2, 3, 55 rather than just regular number with decimal.

I tried using pattern but it didn't seems to work its magic as its still only accepting number and decimal.

Example:
<input type="number" pattern="[0-9]+([\.,][0-9]+)?">

Desired:
<input type="text" pattern="[0-9]+([\.,][0-9]+)?" value="1, 2, 3, 4">

<input type="number" pattern="[0-9]+([\.,][0-9]+)?">

Upvotes: 7

Views: 76220

Answers (4)

CodeToLife
CodeToLife

Reputation: 4141

A chunk of my working html form :

<div class="input-group input-group-auto  col-auto">
    <input class="form-control  text-center"
      oninput="this.value=this.value.replace(/[^0-9,]/g,'');"
      type="text"   id="telefonlar" name="telefonlar" required
    />
</div>

allows only figures , comma and space as you can see in regex expression

Upvotes: 0

clabe45
clabe45

Reputation: 2454

You could use a regular <input type="text"/> with some regex behind it:

var input = document.querySelector('input');
input.addEventListener('input', function() {
  this.value = this.value.replace(/[^0-9 \,]/, '');
});
<input type="text"/>

Regular expression meaning:

[^0-9 \,]    # any character that's not a digit, a space, or a comma

Upvotes: 11

heysulo
heysulo

Reputation: 182

see if this can help you. Patterns are Regular Expressions. Look into regex for more customizations.

<form>
  <input type="text" pattern="([0-9]+.{0,1}[0-9]*,{0,1})*[0-9]" required>
  <input type="submit">
</form>

Upvotes: 2

aahhaa
aahhaa

Reputation: 2275

You should just use type=text and validated/format it using js.

$('input').on('change, keyup', function() {
    var currentInput = $(this).val();
    var fixedInput = currentInput.replace(/[A-Za-z!@#$%^&*()]/g, '');
    $(this).val(fixedInput);
    console.log(fixedInput);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text"/>

Upvotes: 9

Related Questions