I was looking at make an input only-numeric type on knockout.
The accepted answer works fine but how can a more than one decimal point (like 4.4.4) be prevented from being entered (or how can a second decimal point be prevented)?
the code goes like this:
<input id="text" type="text" data-bind="numeric, value: number">
ko.bindingHandlers.numeric = {
init: function (element, valueAccessor) {
$(element).on("keydown", function (event) {
// Allow: backspace, delete, tab, escape, and enter
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: . ,
(event.keyCode == 188 || event.keyCode == 190 || event.keyCode == 110) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
event.preventDefault();
}
}
});
}
};
The custom binding does not look good for me. I'd recommend just using Knockout Validation, which proved a great plugin in my workflow with knockout. The syntax is easy: ko.observable(...).extend({ number: true }). You may also add min/max validation: .extend({ number: true, min: 0, max: 100 }) // percentage and the plugin allows to add css classes to invalid elements.
See example below. It does just what you want.
function viewModel() {
this.number = ko.observable(0).extend({ number: true });
}
ko.applyBindings(new viewModel(), document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.js"></script>
<input data-bind="textinput: number" />
Related
I have some js function what don't allow few special characters, chars etc...
Some users using paste and with paste all chars and special characters are allowed.
$(document).ready(function () {
//called when key is down
$("#recipient").bind("keydown", function (event) {
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || event.keyCode == 188 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: Ctrl+C
(event.keyCode == 67 && event.ctrlKey === true) ||
// Allow: Ctrl+V
(event.keyCode == 86 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
} else {
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-control" type="text" id="recipient" name="recipient" required="required" minlength="9">
This textarea is for phonenumber, it need to be like : 123123123. How change code to dont paste phonenumber with "-" or spaces if someone paste number "123-123-123" or "123 123 123"?
Update: You could use .replace() to filter nonnumeric into empty string and use input instead of keydown to get the correct value of current input
$(document).ready(function () {
//called when key is down
$("#recipient").bind("input", function (event) {
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || event.keyCode == 188 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: Ctrl+C
(event.keyCode == 67 && event.ctrlKey === true) ||
// Allow: Ctrl+V
(event.keyCode == 86 && event.ctrlKey === true) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
} else {
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
console.log(event.target.value)
var numeric = event.target.value.replace(/[^0-9,]/g, '')//replace non-numeric into empty string
console.log('numeric', numeric)
$('#recipient').val(numeric)
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-control" type="text" id="recipient" name="recipient" required="required" minlength="9">
Maybe the most simple and clear way is to use a regex to replace invalid characters:
$(document).ready(function () {
$("#recipient").bind("input", function (event) {
$('#recipient').val($('#recipient').val().replace(/\D/g,""))
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="form-control" type="text" id="recipient" name="recipient" required="required" minlength="9">
Javascript has a more simpler solution.
For formatting your phone number in real time as the user types, you can just get the values from the input box and then use,
input.oninput = function() {}
OR
For formatting your phone number stored in the clipboard, you can get the values from the clipboard by using
input.onpaste = function(event){}
You can make the functions that I've used smaller by removing the tempText & formattedText variables if you like, I used only them for code legibility and for the convenience of the user to use the variables elsewhere on the code.
/* Function 1 */
input.oninput = function() {
var regExpr = /[^0-9,^,]/g; //If you don't want ',' comma then remove ^, from the code between [ ]
var tempText = input.value;
var formattedText = tempText.replace(regExpr, "");
result.innerHTML = formattedText;
};
/* Function 2 */
input.onpaste = function(event) {
var regExpr = /[^0-9,^,]/g; //If you don't want ',' comma then remove ^, from the code between [ ]
var tempText = event.clipboardData.getData('text/plain');
var formattedText = tempText.replace(regExpr, "");
result.innerHTML = formattedText;
};
/*Has nothing to do with the paste formatting*/
body {
display: flex;
flex-direction: column;
height: 80vh;
justify-content: center;
align-items: center;
background: #222;
color: #eee;
text-align: center;
font-family: monospace;
font-size: 1.2em;
}
#input {
text-align: center
}
<body>
<div class="centerAll">
<form>
<label><b>Enter Phone Number</b></label><br/>
<input type="phone" id="input" placeholder="Enter Phone Number...">
<br/>
<br/> Copy paste this:<br/>123-123-123,123<br/>
<br/> Entered Phone number is:<br/>
<span id="result"></span>
</form>
</div>
</body>
I hope this helps...
Peace 🖖
I want to allow both number pad numeric and oridinary number from keyboard. Currently, it only allows the number key row. I also only want numbers to be entered, but it currently allows special characters.
$(document).ready(function() {
$('#price').keydown(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) && event.which != 8) {
event.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='price'>
Have a look at this plug-in (Fork of texotela's numeric jquery plugin). This (jStepper) is another one.
This is a link if you want to build it yourself.
$(document).ready(function() {
$("#txtboxToFilter").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A, Command+A
(e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
NOTE: If your webpage uses HTML5, you can use the built-in <input type="number"> and use the min and max properties to control the minimum and maximum value.
$(function() {
$('#staticParent').on('keydown', '#child', function(e){-1!==$.inArray(e.keyCode,[46,8,9,27,13,110,190])||(/65|67|86|88/.test(e.keyCode)&&(e.ctrlKey===true||e.metaKey===true))&&(!0===e.ctrlKey||!0===e.metaKey)||35<=e.keyCode&&40>=e.keyCode||(e.shiftKey||48>e.keyCode||57<e.keyCode)&&(96>e.keyCode||105<e.keyCode)&&e.preventDefault()});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="staticParent">
<input id="child" type="textarea" />
</div>
I coppied from it on here
If its help for you.Please vote first writer .
Updated your code
$(document).ready(function() {
$('#price').keydown(function(event) {
if((event.which >= 48 && event.which <= 57) && event.shiftKey) {
event.preventDefault();
}
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) && event.which != 8) {
event.preventDefault();
}
});
});
Use keypress for that instead of keydown
then
the keyCode of 0 to 9 are 48 to 57 so use this condition
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
this condition returns true if you enter keys that are not 0, 1, 2, 3, 4, 5, 6, 7 ,8 and 9 or not numbers
So your code would be like this
$(document).ready(function() {
$('#price').keypress(function(event) {
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='price'>
Why we don't user input type number. I think just do it easy like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='number' id='price'>
$('.alphaOnly').bind('keypress', function(event){
var regex = new RegExp("^[ A-Za-z-.']*$");
validation(event, regex);
});
This is my validation for number only in a input. It works prefectly on desktop, iphone but not in android specifically samsung phone.
Does anyone of you ever encountered this kindof problem?
There are two way to achieve this.
1. Use onkeypress event of javascript and allow to enter numeric value only. In this way you will not able to enter decimal values.
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>
Check below snippet. In this way you will be able to enter decimal values.
$(document).ready(function() {
$("#txtboxToFilter").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: Ctrl+C
(e.keyCode == 67 && e.ctrlKey === true) ||
// Allow: Ctrl+X
(e.keyCode == 88 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<input type="text" id="txtboxToFilter" />
Maybe you should try this way
var regex = new RegExp('\\d');
Have no Samsung, but on my android device works as it should
jsfiddle.
I have a function which acts on keydown event and I want it to allow only numbers, backspace and 1 dot. I can't make it work. Here is what I tried:
$('#input[type="number"]').keydown(function(e) {
this.value = this.value.toLowerCase();
var regex = new RegExp("^[0-9.,\b]+$");
var key = String.fromCharCode(!e.charCode ? e.which : e.charCode);
if (!regex.test(key)) {
console.log('stop now')
e.preventDefault();
return false;
}
});
It still prevents dot, but allows numbers. I think my Regex is wrong and needs a tweak.
The comment is gone, but some user suggested that it could be to do with the escaping of the . and , ?? Any ideas?
Use keypress insetead of the keydown event. There are different charcodes sent for some keys for the keydown event. The dot is one of them, sending code 190 instead of the ASCII 46. You can play around with it here.
you can use this instead of using regex. I think This will help you
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript" language="jscript">
function fncInputNumericValuesOnly() {
if (!(event.keyCode == 32 || event.keyCode == 46 || event.keyCode == 48 || event.keyCode == 49 || event.keyCode == 50 || event.keyCode == 51 || event.keyCode == 52 || event.keyCode == 53 || event.keyCode == 54 || event.keyCode == 55 || event.keyCode == 56 || event.keyCode == 57))
{
event.returnValue = false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtEmpName" onkeypress="fncInputNumericValuesOnly()" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
My answer comes a little late but here I've changed your code to something which may work for you:
var valid_value = '';
$('#input[type="number"]').keyup(function(e) {
var regex = new RegExp(/^[0-9]*\.?[0-9]*$/);
if (!regex.test(this.value)) {
this.value = valid_value;
console.log('stop now');
} else {
valid_value = this.value;
}
});
Have you ever tried something like that?
Of course is not perfect but you can assume it as a starter point:
var whitelist = /^\d+\.?\d+?[\b]?$/;
function testInput() {
var val = document.getElementById('val').value;
var res = document.getElementById('res');
if(whitelist.test(val)) {
res.innerText = 'YEP';
} else {
res.innerText = 'NOOPE';
}
}
<input onchange="testInput()" type="text" id="val"/>
<h1 id="res"></h1>
This is what I came up with in the end. A little manual but does the trick!
$('#input[type="number"]').keydown(function(e) {
if (!(e.keyCode == 190 || e.keyCode == 8 || e.keyCode == 9 || e.keyCode == 13 || e.keyCode == 32 || e.keyCode == 46 || e.keyCode == 48 || e.keyCode == 49 || e.keyCode == 50 || e.keyCode == 51 || e.keyCode == 52 || e.keyCode == 53 || e.keyCode == 54 || e.keyCode == 55 || e.keyCode == 56 || e.keyCode == 57)) {
e.returnValue = false;
e.preventDefault();
return false;
}
});
A bit late to the party, but this would work.
edit: click run code snippit before you downvote
var onlySome = restrictKeys([8,190]) // allow the dot
// decorate the jquery function with some functional goodness
$('input[type="text"]').keydown(onlySome(function(e) {
stackLog(['key alowed', e.which, String.fromCharCode(e.which)]);
}));
// functional function to partially apply restricted keys and callback functiion
function restrictKeys(keys) {
return function(fn) {
return function(e) {
// all codes between 48 and 57 are number and cool to leave in, then just filter out our array
if ((e.which < 48 || e.which > 57) && keys.indexOf(e.which) < 0) {
stackLog(['nope', e.which, String.fromCharCode(e.which)]);
e.preventDefault();
return false
}
return fn.call(this, e);
}
}
}
function stackLog(log) {
var _console = document.querySelector('#console');
_console.innerHTML = JSON.stringify(log) + '\n' + _console.innerHTML;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="enter text here">
<pre id="console"></pre>
I have a textfield of Price.
I want only Integer and Float values in it.
I have done the Integer. But it is not accepting Float values like : 3110.6
Here is my Code DEMO
JS:
$(document).ready(function () {
$("#price").keydown(function (event) {
// Allow only backspace and delete
if (event.keyCode == 46 || event.keyCode == 8) {
// let it happen, don't do anything
} else {
// Ensure that it is a number and stop the keypress
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
}
});
});
HTML:
<input name="price" type="text" id="price">
try this demo
$('#price').keypress(function(event) {
if(event.which == 8 || event.which == 0){
return true;
}
if(event.which < 46 || event.which > 59) {
return false;
//event.preventDefault();
} // prevent if not number/dot
if(event.which == 46 && $(this).val().indexOf('.') != -1) {
return false;
//event.preventDefault();
} // prevent if already dot
});
Simply use this:
<input name="price" type="number" id="price">
And remove your JavaScript code.
Try regular expression
/^[+-]?\d+(\.\d+)?$/
Just test the value of the input on the onchange event.
TRy Demo dot or period has keycode 190
$(document).ready(function() {
$("#price").keydown(function(event) {
// Allow only backspace and delete
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 190 ) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if (event.keyCode < 48 || event.keyCode > 57 ) {
event.preventDefault();
}
}
});
});
But better will be use jquery validator plugin at http://jqueryvalidation.org/ as you dont have to check yourself.
For jquery version see JQUERY VALIDATION