2

I'm trying to create an input with JS. I want the input to show the numeric keyboard after clicking. You'll achieve it by giving the input pattern="\d*" so I tried:

div.innerHTML = '<input pattern="\d*" class="input-mark" type="number" placeholder="randomPlaceholder" step="1" min="1" max="5">';

As you guessed, doesn't work. I tried everything. Giving more slashes and backslashes, nothing worked.

I assume it's easy - but I couldn't figure it out.

ANy help is appreciated.

Charlie
  • 22,886
  • 11
  • 59
  • 90
David Stančík
  • 340
  • 6
  • 23

3 Answers3

3

You need to escape the \ in \d to get the \ in the result. See the corrected code below.

document.getElementById("demo").innerHTML = '<input pattern="\\d*" class="input-mark" type="number" placeholder="randomPlaceholder" step="1" min="1" max="5">';

console.log('<input pattern="\\d*" class="input-mark" type="number" placeholder="randomPlaceholder" step="1" min="1" max="5">');
<div id="demo"></div>

This would work.

Pedram
  • 15,766
  • 10
  • 44
  • 73
Vivek
  • 2,665
  • 1
  • 18
  • 20
1

The pattern is to define the input pattern. You will have to use inputmode in conjunction with this.

 <input type="number" pattern="[0-9]*" inputmode="numeric">
Charlie
  • 22,886
  • 11
  • 59
  • 90
  • 1
    Without the `pattern`, without `inputmode` it should work because the `type number`, the problem here is `slash`. This is not really answer of this question. – Pedram Jan 10 '18 at 06:56
0

Try this.

var x = document.createElement( 'input' ),
    div = document.getElementsByTagName( 'div' )[0]; // Just assuming

x.className = 'input-mark';
x.setAttribute( 'type', 'number' );
x.setAttribute( 'placeholder', 'randomPlaceholder' );
x.setAttribute( 'step', 1 );
x.setAttribute( 'min', 1 );
x.setAttribute( 'max', 5 );
x.setAttribute( 'pattern', '\\d*' );
div.appendChild( x );

https://jsfiddle.net/mu9s2m24/

Stev Ngo
  • 94
  • 4