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);
});
Related
Getting input values with the same class name and replacing the value along with % symbol and it shouldn't be a string or object the type should be "number".
Eg: if I enter 25 in the input field it should be changed to 25% and that 25% should be number, not a string.
If your input is of type="number", you can't have a non-numeric character (%) in its value. You could add a label to your input to display the percentage sign right after it, something like this.
<input style="width:40px" type="number" id="myNumericInput" name="myInput"/>
<label for="myInput" style="font-weight: bold">%</label>
You can just apply parseFloat on the input's value, as that will stop parsing as soon as it encounters the %-sign. So the digits that precede it, get evaluated.
You already made that the %-sign is added. You may also want to remove it again, when the user comes back to that input, and starts editing again.
If you want, you could make a little jQuery plugin to make this addition/removal of the %-sign happen whenever the user focusses on the input or steps away from it.
Here is a live snippet: edit and tab away and back to the input-element to see what it does.
// Define jQuery plugin:
$.fn.percentage = function () {
function clean() {
return this.value = this.value.replace(/[^\d.]/g, "");
}
this.each(function () {
$(this).on("focus", clean)
.on("blur", function () {
if (clean.call(this)) this.value += "%";
});
});
}
// Demo
// 1. Automatically add/remove %:
$("input").percentage();
// 2. Illustrate the use of parseFloat
$("input").on("change", function () {
console.log(parseFloat($(this).val()));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input>
I trying to get cursor position inside input field, which is type number
<input type="number" id="myInput">
And I tried standard selectionStart property, but apparently it does not work for number fields.
var start = document.getElementById("myInput").selectionStart;
Is there any why or workaround to get that information inside keypress event?
My end goal is it prevent leading zeros in such input field, for that I need to know is user input coming to start of existing value.
Currently I stripping those zeros in keyup event:
var inputFieldValue = $(this).val();
$(this).val(removeLeadingZeros(inputFieldValue)); // removeLeadingZeros: inputString.replace(/^0+/, "");
But with that solution those zeros became visible for a second before been removed,
that behavior I want to prevent.
Any ideas? How I can get end result string before it provided to user inside input element? Even as selectionStart value not available for number input, browser somehow know where to put those new characters, so there must be some way to capture that and may be prevent some default behavior or stop bubbling.
You can try RegExp
<input type="number" id="myInput">
$("#myInput").on("input", function() {
if (/^0/.test(this.value)) {
this.value = this.value.replace(/^0/, "")
}
});
Does anyone know if it's possible to add a plus sign in a html input type=number field? I have a scenario whereby users need to enter a modifier value which is either +1 to +10 or -1 to -10. I want to make it very explicit to the user that their inputted value increments the resulting value. therefore it would be great if a + sign is prepended to a positive inputted value.
I'm using this input in an Angular2 reactive form with bootstrap styling. so an Angular2 directive, a boostrap style or even a jquery solution are welcome
What I've seen so far is about adding currency symbols inside the form control or about adding + and minus buttons to increment and decrement the value. But that's not what I want, so I doubt if this is possible at all.
I don't think it is possible to manipulate the input.
The default behavior is "-" for negative and no sign for positive numbers.
Even if you checked some custom UI frameworks like:
JQuery UI, Bootstrap, Angular Material ... you will not get the wished behavior.
I guess the only solution for this is to write your own custom code.
Two scenarios are possible:
1- An input with Text and the manipulating will be done in Javascript.
2- Create a pipe in angular2 and give it to the element which I think is much easier than the first one.
No it's not possible. The number field only accepts -, 0-9 and e to be entered. As a workaround you could place the + in the HTML before the input, eg:
+ <input type="number" />
Alternatively you could use a standard type="text" input, but that would mean creating your own validation logic which would make the code much more complex.
I hope this will help on you guys!!
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).on('keypress','#input',function (e) {
var keyCode = e.which;
if ($(this).val().trim().charAt(0) == "\u002B") {
if ( keyCode == 43 ) {
return false;
}
}
else{
for (var i = 1; i < $(this).val().length+1; i++) {
if(i!=0){
if ( keyCode == 43 ) {
return false;
}
}
}
}
});
$(document).on('input', '#input', function() {
this.value = this.value.replace(/[^+{1}|^0-9]/g,'');
});
</script>
I am trying to come up with a solution for converting dot to comma in an input field with type="number", using either JS or JQuery.
The problem is two-fold:
1) It needs to replace the dot no matter where it is located in the input field. Values can be for example:
0.50
.45
12.45
12.
2) I can't use keyup as the trigger. This field is being populated by an externally connected scale, which sends the number, including the dot, in one go.
I hope someone can help with this, it's really doing my head in.
** UPDATE **
I managed to get this piece of code to work, but only if the input is TEXT. If I use NUMBER it just wipes the input clean (and I need it to be NUMBER in order to perform other on-page calculations with the number).
document.getElementById('purchaseQuantity').addEventListener('input', function() {
document.getElementById('purchaseQuantity').value = this.value.replace('.', ',')
});
Thanks,
Use a hidden field with name and update the value within the handler.
document.getElementById('number').addEventListener('input', function() {
document.getElementById('hidden').value = this.value.replace('.', ',')
})
<input type="number" id="number" />
<input type="hidden" name="number" id="hidden" />
var numComma = (value.toString()).replace(".", ",")
Convert the number to string and then use .replace(".",",")
I am having a bit of a hard time figuring out how to only allow user to input numbers 0-9 in an <input type="number" /> as it also allwos other things like eE.+ - etc..
Looked at regex solutions here on stack overflow and each one seems to have an issue i.e. if there are no numbers in an input you can type in any of unwanted characters, if you typed in a number you can't delete it completely as there needs to be at least 1 digit.
using keycodes introduces an issue as event.target.value is not avaliable on key events, it seems to only be available in onchange, however in this case e.which is not avaliable to check key pressed.
Do you mean you only want users to be able to enter digits 0-9?
var input = document.getElementById("only-digits");
input.onkeydown = function(e) {
if (48 > e.which || e.which > 57)
if (e.key.length === 1)
e.preventDefault();
};
<input type="number" id="only-digits">
I'm making sure that the key the user presses is only a 0, 1, 2, ... 9 character using the range of their ASCII values.
If the key they pressed was outside of that range, then I make sure it is a word character and then I prevent it from being entered into the text field.
you can use the regex attribute on the html input field:
<input pattern="[0-9]*">
this allows only for 0-9 characters, zero or multiple times
<input pattern="[0-9]+">
this allows only for 0-9 characters, 1 or multiple times
update
it doesn't work with type="number" though, if you want it to work with this, you need to use javascript. See the other answers for this.
You can prevent user when he/she enters any character other than Number
See the below code
HTML
<input type=number class="numberOnlyInput" oncopy="return false" onpaste="return false" ondrag="return false">
JQuery
$(document).on('keypress','.numberOnlyInput',function(e){
if(!(e.keyCode >=48 && e.keyCode <=57) ){
e.preventDefault();
}
});
You can see the demo here:
https://jsfiddle.net/cnosh74e/