I am trying to get an input to be also for numbers (opening a number
keyboard in mobile + up and down arrows) and making it like search
type - adding "X" before the input if there is data inside it
You have two options:
Have an input
of type=search
and define a pattern
attribute to it. This way it will fire numeric keyboard on mobiles solving your first number requirement. However, it will not show up-down spinners. If you could do without the spinners, then this is the easiest option. Just markup the input
like this: <input type="search" pattern="\d*" />
. The pattern
\d*
will force the validator to accept only digits. You can devise this regex as per your use-case.
You could use an input
of type=number
, which will solve both of your number problems. It will fire the numeric keyboard as well as show the spinners. This being a number type, will also automatically fire the validator if a non-numeric value is submitted. However, to make it behave like a search
box, you will have to hack a cross into it using an extra span
and some CSS. Moreover, you will need some Javascript to clear the input
when the cross is clicked.
Here is a very crude example of both the options. Also, note that this may not be a truly cross-browser solution. For example, IE will happily ignore the type=number
and actually show a cross at the right.
Demo Fiddle: http://jsfiddle.net/abhitalks/hgn7roje/
Demo Snippet:
$("span.closer").on("click", function(e) {
if (e.target.tagName == 'SPAN') {
$(this).children("input").val('');
}
});
span.closer {
display: inline-block;
position: relative;
}
span.closer::before {
content: '×'; font-weight: bold;
position: absolute; cursor: pointer;
left: 4px; top: 2px;
}
span.closer:hover::before {
color: #00f;
}
input[type=number] {
padding-left: 16px;
width: 220px;
}
input[type=number]:invalid {
border: 1px solid red;
}
input[type=search] {
width: 240px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label>Option 1: </label>
<input type="search" pattern="\d*" />
<input type="submit" value="Search" />
</form>
<br />
<form>
<label>Option 2: </label>
<span class="closer"><input type="number" /></span>
<input type="submit" value="Search" />
</form>