I couldn't find any solution for selecting a range of characters in a <input type="number"> field.
Is it possible?
EDIT: I'm sorry I didn't mention it. By "range", I meant setSelectionRange().
You really should not be asking questions like that here.
With a simple search you could have figured it out.
I will answer it for you however and also assume you mean 'Number' instead of 'Characters'.
You also have to take into account that this is HTML5 and can have browser compatibility issues and you will need to add a polyfill for older browsers.
You can also use step = "any" to specify the value granularity of the value.
<input type="number" name="quantity" min="1" max="5">
Further to the response from #Scor3keeper if you want to handle this yourself rather than relying on the browser's implementation of min/max you could do something like this:
<script>
function handleChange(input) {
if (input.value < 0) input.value = 0;
if (input.value > 100) input.value = 100;
}
</script>
Then declare the input box like this:
<input type="text" onchange="handleChange(this);" />
This is slightly more robust than modern browser's implementation which allows you to paste or type numbers out of range. However the browser implementation does give the user validation alerts.
Related
Can I have a number input element where the digits are entered right to left without manual cursor movement in between? The application is for training basic mental arithmetic, where that order is more natural.
I'd like to also have my input element configured as a number. Both the automatic addition of stepper buttons on desktop and the choice of a numeric keyboard on mobile devices are beneficial.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange writes:
Note that according to the WHATWG forms spec selectionStart, selectionEnd properties and setSelectionRange method apply only to inputs of types text, search, URL, tel and password. Chrome, starting from version 33, throws an exception while accessing those properties and method on the rest of input types. For example, on input of type number: "Failed to read the 'selectionStart' property from 'HTMLInputElement': The input element's type ('number') does not support selection".
And indeed, while I can get what I want fairly easily for a text input, it fails for me on recent Chrome with a number input element, as my demo below shows. The current selection endpoints are always null for a number input element.
Is there any way to work around the restrictions and manipulate the cursor / caret position of a number element? Or, barring that, any way to make a text element reject non-digit input, show a stepper and use a numeric keyboard, ideally without linking in heavy library dependencies like Angular?
const dbg = document.getElementById("dbg");
["txt", "num"].forEach(id => {
const elt = document.getElementById(id);
elt.addEventListener("input", evnt => {
dbg.innerText = `evnt.inputType = ${evnt.inputType}, elt.selectionStart = ${elt.selectionStart}, elt.selectionEnd = ${elt.selectionEnd}`;
if (evnt.inputType == "insertText" &&
elt.selectionStart === 1 &&
elt.selectionEnd === 1) {
elt.setSelectionRange(0, 0);
}
});
});
<p>Text: <input type="text" id="txt"></p>
<p>Number: <input type="number" id="num"></p>
<p>Debug: <span id="dbg"></span></p>
You can do that using CSS.
<p>Text: <input type="text" id="txt" style="direction: rtl"></p>
<p>Number: <input type="number" id="num" style="direction: rtl"></p>
<p>Debug: <span id="dbg" ></span></p>
i have input with type number like this
<input type="number" class="number" min="0" max="999999" value="0" id="id">
when i use this code
$("#id").val();
if it's number like 1 it return the number
but if not a number like 1+1 it return empty string ""
so can i get the actual value with type number or i have to change to text to do so
i test it with chrome and firefox
i know that it will work with type text
but i'm looking to faster solution if there are non then i will change it to text and rewrite the code
here is my question
now when i change the type to text using jquery it remove the value can i change it without remove the value ?
$('#id').attr('type','text')
what i want to do is make the type text get the value and return it back to number
You can not do it with <input type='number'/>,
<input type="number" > will expect you to put a number, so if you put anything like 1+1, it is not considered a number, so returns an empty string "".
you can instead use <input type=text/>
See this fiddle
$('input').on('change', function() {
var strVal = $("#id").val();
var intVal = eval(strVal);
alert(intVal);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="number" value="0" id="id">
Edit:
if you cant change whole html, you can change type of the element using jquery,
$('input[type=number]').attr('type','text')
just put this on page load
If someone needs an input type="number" , there is a reason.
Premise: I'm not the same Robert that made the initial question :-)
but ...
I was exactly in the same situation of the Robert who made the initial question ( destiny matter? ), anyway
making a deeper research, I have found this answer
JavaScript get clipboard data on paste event (Cross browser)
I beloved that twice because, nevertheless, it is pure vanilla javascript
I have made this code with input type = "number" and it works like a charm
The main behavior because I want input type = "number" is that this input type, when focused ON MOBILE will open the numbers pad INSTEAD than the letters keyboard. Here the input is driven, you can press only numbers and dashes
But in my app , they can paste the number.. so having a check on the paste event, is a logical consequence
try it
function handlePaste (e) {
var clipboardData, pastedData;
// Stop data actually being pasted into div
e.stopPropagation();
e.preventDefault();
// Get pasted data via clipboard API
clipboardData = e.clipboardData || window.clipboardData;
pastedData = clipboardData.getData('Text');
// Do whatever with pasteddata
alert(pastedData);
}
document.getElementById('myInput').addEventListener('paste', handlePaste);
<p>This example uses the addEventListener() method to attach a "paste" event to an input type="number" element. Paste some text in the input...</p>
<input type="number" id="myInput" value="Try to paste something in here" size="40">
OK Solution to your problem
$('input[type=number]').each(function(){
var val = $(this).val();
$(this).attr('type','text');
$(this).val(val);
});
above code will work on all inputs with type number. If you want to use only one use class or id in first line. If you want to count value from string like 1+1 u can use eval in try catch block. But this is generally a lot more complicated solution.
Is there a possiblity to force an iOS-device to show the numeric keyboard while using a custom pattern as input type?
my input pattern:
<input id="price" class="numeric" pattern="\d+((\.|,)\d{1,2})?" name="price"
title="" data-mini="true" data-clear-btn="true" autocomplete="off" autofocus />
I want to type a currency value like '14.99' and show up a keyboard with access to numbers on the iOS device
<input type='number' />
<input pattern='[0-9]*' />
<input pattern='[\d]*' />
are all missing the decimal sign and/or are not validating as number when adding a decimal sign. An alternative way could be a javascript function which is creating the decimal sign on the right place, like pressing 1->2->9->9 in this order creates on keypress() 0.01->0.12->1.29->12.99,
but this requires the input field to be type='text' --> obvious problem here is that the text keyboard is showed when focussing the input field.
How can I solve this issue?
EDIT
Environment:
JQM 1.3.2
jquery 1.8.2
For now, JavaScript is the only solution. Here's the simplest way to do it (using jQuery):
HTML
<input type="text">
JavaScript
$('input[type="text"]').on('touchstart', function() {
$(this).attr('type', 'number');
});
$('input[type="text"]').on('keydown blur', function() {
$(this).attr('type', 'text');
});
The idea is simple. The input starts off and ends up with type="text", but it briefly becomes type="number" on the touchstart event. This causes the correct iOS keyboard to appear. As soon as the user begins to enter any input or leave the field, the input becomes type="text" once again, thus circumventing the validation.
There's one downside to this method. When the user returns to an input that has already been filled out, the input will be lost (if it doesn't validate). This means the user won't be able to go back and edit previous fields. In my case, this isn't all that bad because the user may want to use the calculator over and over again with different values, so automatically deleting the input will save them a few steps. However, this may not be ideal in all cases.
It looks like Mobile Safari supports the new HTML5 input type attributes of email, number, search, tel, and url. These will switch the keyboard that is displayed. See the type attribute.
So for example, you could do this:
<input type="number" />
And when the input box has focus, the number keyboard is shown (as if the user had the full keyboard and hit the "123" button.
If you really only want numbers, you could specify:
<input type="tel" />
And then the user would get the phone number dialing keypad.
I know this works with Mobile Safari -- I only assume it will work with UIWebView.
http://conecode.com/news/2011/12/mobile-safari-uiwebview-input-types/
I made this little snippet to achieve what you want and I've tested it on iPhone 5 v7.0.3
I used e.which to read CharCode entered and then push it into an array (before) which represents digits before decimal mark and another array (after) to move values from (before) array past the decimal mark.
It might look complicated, due to my humble programming skills.
1) Code demo - 2) Currency conversion demo
HTML:
<input type="tel" id="number" />
JS
Variables and functions:
// declare variables
var i = 0,
before = [],
after = [],
value = [],
number = '';
// reset all values
function resetVal() {
i = 0;
before = [];
after = [];
value = [];
number = '';
$("#number").val("");
$(".amount").html("");
}
// add thousand separater
function addComma(num) {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
Main code:
// listen to keyup event
$("#number").on("keyup", function (e, v) {
// accept numbers only (0-9)
if ((e.which >= 48) && (e.which <= 57)) {
// convert CharCode into a number
number = String.fromCharCode(e.which);
// hide value in input
$(this).val("");
// main array which holds all numbers
value.push(number);
// array of numbers before decimal mark
before.push(value[i]);
// move numbers past decimal mark
if (i > 1) {
after.push(value[i - 2]);
before.splice(0, 1);
}
// final value
var val_final = after.join("") + "." + before.join("");
// show value separated by comma(s)
$(this).val(addComma(val_final));
// update counter
i++;
// for demo
$(".amount").html(" " + $(this).val());
} else {
// reset values
resetVal();
}
});
Reset:
// clear arrays once clear btn is pressed
$(".ui-input-text .ui-input-clear").on("click", function () {
resetVal();
});
Result:
I think that you can use the same approach that I suggested to Ranjan.
Using a textfield like a buffer. First you need to detect when the keyboard appears and check if the first responder is the webview. Then you become a textview as the first responder.
When you are setting the text inside the input of the webview, you can add some logic to validate the number.
Here is a link of my example project with the solution, in your case you don't need change the inputView. But the approach is the same, use a Man in the middle.
Cant comment on https://stackoverflow.com/a/19998430/6437391 so posting as a separate answer...
This is the same idea as https://stackoverflow.com/a/19998430/6437391 but instead of switching the type, its the pattern that's switched.
This has the effect of not clearing the value on the textfield on focus when value does not match numeric format, for example, if the value has separators( 1,234.56 ).
$('input[type="text"]').on('touchstart', function() {
$(this).attr('pattern', '[0-9]*');
});
$('input[type="text"]').on('focus', function() {
$(this).attr('pattern', actualpattern);
});
If possible i would like to use an input box that i could type "1" to "200" and open the link corresponding to it when applied. All links and input within the same site and folder structure. This would be more favorable than a limited pagination, as well as more mobile friendly.
Full url example to be opened would be: http://example.com/test-1
Currently I have a similar structure with pages that end in "-1" to "-112"
Allowing the following portion pre-determined: "http://example.com/test-"
So that when any number is typed into the input field it would add itself to the pre-determined value listed above. When only "1" or any other number is entered into the field.
Hopefully with compatibility with iOS and most popular browsers. Many Thanks for any help, as i have tried over a dozen other navigation methods, and i feel this would be the best approach. I can do the css and styling of the input, but i'm looking for a light weight approach to handling this query.
This solution works for me. By the way, I like keyboard-input-based interfaces since they are truly the fastest way of navigation yet strangely are not popular in these days of dumbing down people to always push buttons, so I also am voting up your question.
Some features that are important and which I programmed into the code are that this JavaScript navigates without the user needing to push "Go" on their mobile device's keyboard, while also making sure that the user has time to keep typing if they are intending to type a two- or three-digit number.
<input type="text" onkeyup="
if (self.going) clearTimeout(self.going);
var x = this.value.replace(/\D+/g, '');
if (!x) return;
self.going = setTimeout(function() {
var url = 'http://example.com/test-' + x;
/* alert(url); */
location.href = url;
}, 1000);
" placeholder="Enter 1-112!" />
Customization options:
By changing 1000 to a different value, you can customize the slight pause before navigation begins (at risk of prematurely leaving the page before the user has finished typing).
This is pretty straighforward:
<input type='text' placeholder='Enter a number' id='number' />
<input type='button' value='Go' id="go" />
<p>Please enter a number above.</p>
jQuery/JS:
$('#go').on('click', function(event) {
var num = $('#number').val();
if (num == "") return;
var url = "http://example.com/test-" + num;
window.location.href = url;
});
Example
http://codepen.io/hamstu/pen/shdjv
Can someone show me some example for restricting user input (on input tag) in Javascript?
Something that when we set the input (type="text") to only accept numeric, so it will ignore any other input except for numeric...
I think it's handy for number input (such as zip, credit card, money, value, score, date etc...), and if you can please show me how to create input with pattern, something like:
Please Input Date:
|-----------------|
| / / |
|-----------------|
PS:
I heard WebForms 2.0 will support this in the future... (Acid 3 compliant browser?)
input type="date"
input type="time"
input type="number"
input type="money"
But it was only news from future :D
This might help you.
http://www.w3schools.com/jsref/event_onkeydown.asp
<html>
<body>
<script type="text/javascript">
function noNumbers(e)
{
var keynum;
var keychar;
var numcheck;
if(window.event) // IE
{
keynum = e.keyCode;
}
else if(e.which) // Netscape/Firefox/Opera
{
keynum = e.which;
}
keychar = String.fromCharCode(keynum);
numcheck = /\d/;
return !numcheck.test(keychar);
}
</script>
<form>
<input type="text" onkeydown="return noNumbers(event)" />
</form>
</body>
</html>
This question has already an accepted answer, but I think there is a better solution to this. You don't have to implement that yourself on keydown etc., there are libraries for that. They call the technique you describe "input masks". Check out this jQuery plugin it does exactly what you want.
You can use specific libs like jQuery Validate (or whatever your JS framework offers) on form submit. The other solution is to control the value on the keyUp & blur events but it can become quite messy to decide what to do with ill-formated entry (especially when the format is a bit complex -- ie not just undesired characters). So, all in all, I'd recommend client-side control on submit.