Related
I have a textbox and it contain a value "Given Name". I want to disable first character of a textbox so that user cannot change the First Charcter in textbox by using backspace or any other means.
For Example: suppose textbox contains the value "Given Name". I want that user cannot change the First character "G" by using backspace or any other means.
<input type="text" id="nameId" onkeydown="validate(this.val)"/>
Below is javascript function:
function validate2(val) {
// have no idea how to do.
}
I have no idea how to do it in Javscript or Jquery.
You could do like follow :
$("#nameId").on("keydown", function(e) {
// if user writes a char at index === 0 that is not an arrow or HOME or END
if (($(this).get(0).selectionStart === 0 && (e.keyCode < 35 || e.keyCode > 40))
// or if user tries to erase first char
|| ($(this).get(0).selectionStart === 1 && $(this).get(0).selectionEnd === 1 && e.keyCode === 8)) {
// don't write the character
return false;
}
});
// prevent right click
$("#nameId").bind("contextmenu", function(e) {
e.preventDefault();
});
JSFIDDLE
Wasn't planning on answering, leaving it with the comment, but after seeing the other answers thought I might have a quick go at it after all:
The html:
<input type="text" id="nameId" value="Given Name" onkeydown="save(this,event)" onkeyup="restore(this,event)" onchange="restore(this,event)"/>
The javascript:
function restore(el,event) {
if(el.value.length == 0){
el.value = el.dataset.value.substr(0,1);
}else{
el.dataset.value = el.value;
}
}
function save(el,event) {
var key = event.which || event.charCode || event.keyCode;
if((key === 8 && el.value.length === 1)
|| (key === 46 && el.selectionStart == 0 && el.value.length === 1)){
event.preventDefault();
}
if(el.value.length > 0){
el.dataset.value = el.value;
}
}
The approach was to not mess around too much with preventing the deletion of the actual character (just the very bare basics) and instead ensure that if somebody deletes the first character to always restore it somehow. It creates code that's easy to comprehend and maintain, yet works quite neatly. A fiddle can be found here as well. Do note though that event.which is not the most cross browser consistent interface, so either use jQuery for that or check in other browsers before using it in production. Edited it in a way that should work cross browser including older browsers.
Here's mine version.
Html
<input type="text" id="nameId" value="Given Name" />
JS
var lastentry = '';
$("#nameId").on("keyup", function(e) {
var targetValue = $(e.currentTarget).attr('value');
var targetValueLength = targetValue.length;
var inputValue = this.value;
if(checkChanges(targetValueLength, targetValue, inputValue))
this.value = targetValue + lastentry;
else
lastentry = this.value.slice(targetValueLength)
});
function checkChanges(targetValueLength, targetValue, inputValue)
{
for(var i = 0; i < targetValueLength ; i++)
{
if(targetValue[i] != inputValue[i])
return true;
}
return false;
}
Demo
You can try this:-
<input type="text" id="nameId" value="Given Name" onkeydown="validate(this.value,event)"/>
<script>
function validate(val,event) {
// have no idea how to do.
if(event.target.selectionStart != undefined && (event.which === 46 ||event.which === 8)){
var startPos = event.target.selectionStart,
endPos = event.target.selectionEnd;
console.log(startPos,endPos);
if(startPos === 0 && startPos != endPos){
var restPart = val.slice(endPos,val.length);
if(restPart){
val = val[0].concat(restPart);
} else{
val = val[0]
}
event.target.value = val;
event.preventDefault();
} else if(startPos === 0 && startPos === endPos && event.which === 46){
event.preventDefault();
} else if(startPos === 1 && event.which === 8){
event.preventDefault();
}
}
}
</script>
Hi use this it do not allow to delete first character ,
$(document).keydown(function(e)
{
var value = $('#nameId').val().length;
if ( e.keyCode == 8 && value < 2)
e.preventDefault();
});
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
Guys and gals i have this piece of JavaScript code that only allows for numbers and one decimal period. The problem i'm having is that when i tab over to my textbox controls it highlights the value but i have press backspace to erase then enter a number. That is an extra keystroke that i want to prevent.
Props to the guy who created it found (http://www.coderanch.com/t/114528/HTML-CSS-JavaScript/decimal-point-restriction) and here is the code. I put this on keyUp event.
<script>
// Retrieve last key pressed. Works in IE and Netscape.
// Returns the numeric key code for the key pressed.
function getKey(e)
{
if (window.event)
return window.event.keyCode;
else if (e)
return e.which;
else
return null;
}
function restrictChars(e, obj)
{
var CHAR_AFTER_DP = 2; // number of decimal places
var validList = "0123456789."; // allowed characters in field
var key, keyChar;
key = getKey(e);
if (key == null) return true;
// control keys
// null, backspace, tab, carriage return, escape
if ( key==0 || key==8 || key==9 || key==13 || key==27 )
return true;
// get character
keyChar = String.fromCharCode(key);
// check valid characters
if (validList.indexOf(keyChar) != -1)
{
// check for existing decimal point
var dp = 0;
if( (dp = obj.value.indexOf( ".")) > -1)
{
if( keyChar == ".")
return false; // only one allowed
else
{
// room for more after decimal point?
if( obj.value.length - dp <= CHAR_AFTER_DP)
return true;
}
}
else return true;
}
// not a valid character
return false;
}
</script>
<input type="text" class="decimal" value="" />
And in Js use this
$('.decimal').keyup(function(){
var val = $(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9\.]/g,'');
if(val.split('.').length>2)
val =val.replace(/\.+$/,"");
}
$(this).val(val);
});
Check this fiddle: http://jsfiddle.net/2YW8g/
THis worked for me, i have taken this answer from "Nickalchemist" and take none of its credit.
If you can't use an already stable and well-know library, you can try something like this:
document.write('<input id="inputField" onkeyup="run(this)" />');
function run(field) {
setTimeout(function() {
var regex = /\d*\.?\d?/g;
field.value = regex.exec(field.value);
}, 0);
}
I know it doesn't prevent the wrong char to appear, but it works.
PS: that setTimeout(..., 0) is a trick to execute the function after the value of the field has already been modified.
Here is a sample solution that will accept a number with one(1) decimal point only. e.g 1.12, 11.5
Enter a number with one(1) decimal point only<br />
<input type="text" id="decimalPt"> <br />
$('.decimalPt').keypress(function(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode == 8 || charCode == 37) {
return true;
} else if (charCode == 46 && $(this).val().indexOf('.') != -1) {
return false;
} else if (charCode > 31 && charCode != 46 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
});
Take a look at this: https://jsfiddle.net/sudogem/h43r6g7v/12/
I think it would be best to use something that already exists... like Masked Input Plugin with jQuery
Try this,
$('input').on('keydown', function (event) {
return isNumber(event, this);
});
function isNumber(evt, element) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if ((charCode != 190 || $(element).val().indexOf('.') != -1) // “.” CHECK DOT, AND ONLY ONE.
&& (charCode != 110 || $(element).val().indexOf('.') != -1) // “.” CHECK DOT, AND ONLY ONE.
&& ((charCode < 48 && charCode != 8)
|| (charCode > 57 && charCode < 96)
|| charCode > 105))
return false;
return true;
}
Be sure to test on any browser. The accepted answer doesn't work on Firefox.
Try HTML5 type number:
<input type="number" placeholder="1.0" step="0.1">
You could define min="0" max="10"
Reference:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number#Controlling_input_size
Note: type="number" is not supported in Internet Explorer 9 and earlier versions.
I solve my problem with like this.
const sanitize = (value = '') => value.replace(/(-(?!\d))|[^0-9|-]/g, '') || ''
export const toNumeric = value => {
let digits = sanitize(value)
// parseInt with 0 fix/avoid NaN
digits = parseInt(0 + digits)
let newValue = digits.toString().padStart(4, 0)
return newValue
}
I wanted a text field to take only numbers ans some control keys and number should be exactly four digit long, not less not more. My validation code is
function checkValidInput()
{
$(".validateYearTextBox").keydown(function(event)
{
// Allow only delete, backspace,left arrow,right arraow and Tab
if (
event.keyCode == 46 //delete
|| event.keyCode == 8 //backspace
|| event.keyCode == 37 //leftarow
|| event.keyCode == 39 //rightarrow
|| event.keyCode == 9 //tab
)
{
// 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.keyCode <96 ||event.keyCode > 105) ) {
event.preventDefault();
}
}
});
$(".validateYearTextBox").keyup(function(event)
{
var val = $(this).val();
if (val.length > 4){
alert ("Max length is 4");
val = val.substring(0, valore.length - 1);
$(this).val(val);
$(this).focus();
return false;
}
});
}
Here, my first validation is working, but my send one is not working.
I am calling this validation function in my aspx page like this
<script type="text/javascript">
$(document).ready(function(){
checkValidInput();
}
</script>
What is going wrong?
Simplify it:
function checkValidInput() {
// Allow only delete, backspace, left arrow, right arrow,
// Tab, ctrl+v and numbers
$(".validateYearTextBox").keydown(function(event) {
if (!((event.keyCode == 46 ||
event.keyCode == 8 ||
event.keyCode == 37 ||
event.keyCode == 39 ||
event.keyCode == 9) ||
(event.ctrlKey && event.keyCode == 86) || // Edit: Added to allow ctrl+v
$(this).val().length < 4 &&
((event.keyCode >= 48 && event.keyCode <= 57) ||
(event.keyCode >= 96 && event.keyCode <= 105)))) {
// Stop the event
event.preventDefault();
return false;
}
});
// Edit: Added validate after copy+paste.
// This removes non-numeric characters and truncates the length
// to 4 if the user copy + pasted.
$(".validateYearTextBox").change(function(event) {
var value = $(this).val();
value = value.replace(/[^0-9]/g,'');
value = value.substr(0,4);
$(this).val(value);
});
}
$(document).ready(function() {
checkValidInput();
});
http://jsfiddle.net/nwellcome/687kD/
Edit: Personally I like the Masked Input jQuery plugin but that might be a heavy-handed solution if this is all you need to do.
There are many, many jQuery plugins that already do this in one form or another.
One that does mostly1 what you want is Masked Input Plugin. If you can, I recommend using something existing, working and proven, rather than reinventing.
1 The only part that it doesn't seem to do is display an error if a user tries to enter more than n characters but I'm sure you could modify the plugin or add a length check to the <input>
Use regular expression :
enter code here
function validator(elem,msg)
{
var exp=/^([0-9]+)$/; //it only allows for numbers
if(elem.value.match(exp))
{return true;}
else
{
alert(msg);
elem.focus();
return false;
}
}
the html code :
enter code here
<html><head>
<script src="javasript.js" type="text/javascript">
</head>
<body>
<form method=POST>
<input type='text' maxlength=4 name='num' id='num'>
<input type='submit' value=OK onClick="validator(document.getElementById('num'),'Only four numbers and numbers only!');">
</form> //the maxlength in input text tag restrict the maximum length of the input
</body></html>
Here's a simple way of doing it. Stores the old text before an event changes the text. Then check to see if the new text is valid or not. If it isn't, then revert back to the old text. To further ensure the maximum of 4 characters, add a maxlength attribute to all <input type="text"> elements.
jQuery.fn.forceNumericOnly = function() {
return this.each(function() {
var oldText;
$(this).keyup(function(e) {
var newText = $(this).val();
if (newText != "" && (isNaN(newText) || val.length > 4))
$(this).val(oldText);
else
oldText = $(this).val();
})
$(this).blur(function(e) {
var newText = $(this).val();
if (newText != "" && (isNaN(newText) || val.length > 4))
$(this).val(newText = oldText);
else
oldText = $(this).val();
});
})
};
$(".validateYearTextBox").forceNumericOnly();
if (document.ExamEntry.examnum.value=="") {
msg+="You must enter your examination number \n";
document.ExamEntry.examnum.focus();
document.getElementById('examnum').style.color="red";
result = false;
}
$('.numeric').keypress(function(e) {
var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(/[^0-9]/);
if (verified || e.delegateTarget.value.length>3 || e.ctrlKey ==true) { if(e.which!=8 ){e.preventDefault();}}
}).on('paste',function(e){ e.preventDefault();});
Here add class=numeric to input text box'. it will allow only 4 digits if you want to limit size to 2 digits change to e.delegateTarget.value.length>1 and so on as index starts from zero
Use HTML input maxlength attribute for this and also set the size value of fixing width 4 in same input size attribute.
<input type="text" maxlength="4" size="4">
Here is a simple answer that takes care of copy paste and all.
$(document).on("input", ".validateYearTextBox", function() {
var value = this.value
value = value.replace(/\D/g,'');
for (i = 0; i < value.length; i++) {
if (i > 3) {
value = value.replace(value[i], '')
}
}
});
i'm making some input mask that allows only float number. But current problem is I can't check if multiple dots entered. Can you check those dots and prevent it for me?
Live Code: http://jsfiddle.net/thisizmonster/VRa6n/
$('.number').keypress(function(event) {
if (event.which != 46 && (event.which < 47 || event.which > 59))
{
event.preventDefault();
if ((event.which == 46) && ($(this).indexOf('.') != -1)) {
event.preventDefault();
}
}
});
You can check for the period in the same statement.
Also, you need to use the val method to get the value of the element.
Also, you want to check for the interval 48 to 57, not 47 to 59, otherwise you will also allow /, : and ;.
jQuery(document).ready(function() {
$('.float-number').keypress(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
Enter Number:
<input type="text" name="number" value="" class="float-number">
</body>
</html>
I think you guys have missed the left right arrows, delete and backspace keys.
$('.number').keypress(function(event) {
if(event.which == 8 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46)
return true;
else if((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57))
event.preventDefault();
});
I think everybody forgot the case of pasting text with the mouse, in which you can't detect the keystrokes, because there's none. Here's another approach I have been working on.
// only integer or float numbers (with precision limit)
// example element: <input type="text" value="" class="number" name="number" id="number" placeholder="enter number" />
$('.number').on('keydown keypress keyup paste input', function () {
// allows 123. or .123 which are fine for entering on a MySQL decimal() or float() field
// if more than one dot is detected then erase (or slice) the string till we detect just one dot
// this is likely the case of a paste with the right click mouse button and then a paste (probably others too), the other situations are handled with keydown, keypress, keyup, etc
while ( ($(this).val().split(".").length - 1) > 1 ) {
$(this).val($(this).val().slice(0, -1));
if ( ($(this).val().split(".").length - 1) > 1 ) {
continue;
} else {
return false;
}
}
// replace any character that's not a digit or a dot
$(this).val($(this).val().replace(/[^0-9.]/g, ''));
// now cut the string with the allowed number for the integer and float parts
// integer part controlled with the int_num_allow variable
// float (or decimal) part controlled with the float_num_allow variable
var int_num_allow = 3;
var float_num_allow = 1;
var iof = $(this).val().indexOf(".");
if ( iof != -1 ) {
// this case is a mouse paste (probably also other events) with more numbers before the dot than is allowed
// the number can't be "sanitized" because we can't "cut" the integer part, so we just empty the element and optionally change the placeholder attribute to something meaningful
if ( $(this).val().substring(0, iof).length > int_num_allow ) {
$(this).val('');
// you can remove the placeholder modification if you like
$(this).attr('placeholder', 'invalid number');
}
// cut the decimal part
$(this).val($(this).val().substring(0, iof + float_num_allow + 1));
} else {
$(this).val($(this).val().substring(0, int_num_allow));
}
return true;
});
Good for integer and float values. Plus, copy/paste clipboard event.
var el = $('input[name="numeric"]');
el.prop("autocomplete",false); // remove autocomplete (optional)
el.on('keydown',function(e){
var allowedKeyCodesArr = [9,96,97,98,99,100,101,102,103,104,105,48,49,50,51,52,53,54,55,56,57,8,37,39,109,189,46,110,190]; // allowed keys
if($.inArray(e.keyCode,allowedKeyCodesArr) === -1 && (e.keyCode != 17 && e.keyCode != 86)){ // if event key is not in array and its not Ctrl+V (paste) return false;
e.preventDefault();
} else if($.trim($(this).val()).indexOf('.') > -1 && $.inArray(e.keyCode,[110,190]) != -1){ // if float decimal exists and key is not backspace return fasle;
e.preventDefault();
} else {
return true;
};
}).on('paste',function(e){ // on paste
var pastedTxt = e.originalEvent.clipboardData.getData('Text').replace(/[^0-9.]/g, ''); // get event text and filter out letter characters
if($.isNumeric(pastedTxt)){ // if filtered value is numeric
e.originalEvent.target.value = pastedTxt;
e.preventDefault();
} else { // else
e.originalEvent.target.value = ""; // replace input with blank (optional)
e.preventDefault(); // retur false
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="numeric" value="" placeholder="insert value">
[2017-10-31] Vanilla.js
let el = document.querySelector('input[name="numeric"]');
el.addEventListener('keypress',(event) => {
let k = event.key,
t = isNaN(k),
sc = ['Backspace'].indexOf(k) === -1,
d = k === '.',dV = el.value.indexOf('.') > -1,
m = k === '-',mV = el.value.length > 0;
if((t && sc) && ((d && dV) || (m && dV) || (m && mV) || ((t && !d) && (t && !m)))){event.preventDefault();}
},false);
el.addEventListener('paste',(event) => {
if(event.clipboardData.types.indexOf('text/html') > -1){
if(isNaN(event.clipboardData.getData('text'))){event.preventDefault();}
}
},false);
<input type="text" name="numeric">
Your code seems quite fine but overcomplicated.
First, it is $(this).val().indexOf, because you want to do something with the value.
Second, the event.which == 46 check is inside an if clause that's only passed when event.which != 46, which can never be true.
I ended up with this which works: http://jsfiddle.net/VRa6n/3/.
$('.number').keypress(function(event) {
if(event.which < 46
|| event.which > 59) {
event.preventDefault();
} // prevent if not number/dot
if(event.which == 46
&& $(this).val().indexOf('.') != -1) {
event.preventDefault();
} // prevent if already dot
});
I found this way to do this,
$.validator.addMethod("currency", function (value, element) {
return this.optional(element) || /^\$(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$/.test(value);
}, "Please specify a valid amount");
https://gist.github.com/jonkemp/9094324
HTML
<input type="text" onkeypress="return isFloatNumber(this,event)" />
Javascript
function isFloatNumber(item,evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode==46)
{
var regex = new RegExp(/\./g)
var count = $(item).val().match(regex).length;
if (count > 1)
{
return false;
}
}
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
jsfiddle.net
Using JQuery.
$(document).ready(function()
{
//Only number and one dot
function onlyDecimal(element, decimals)
{
$(element).keypress(function(event)
{
num = $(this).val() ;
num = isNaN(num) || num === '' || num === null ? 0.00 : num ;
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57))
{
event.preventDefault();
}
if($(this).val() == parseFloat(num).toFixed(decimals))
{
event.preventDefault();
}
});
}
onlyDecimal("#TextBox1", 3) ;
});
One-more plugin, based on Carlos Castillo answer
https://github.com/nikita-vanyasin/jquery.numberfield.js
Adds method to jQuery object:
$('input.my_number_field').numberField(options);
where options is (you can pass any or no options):
{
ints: 2, // digits count to the left from separator
floats: 6, // digits count to the right from separator
separator: "."
}
Using jQuery and allowing negative floats :
// Force floats in '.js_floats_only' inputs
$(document).ready(function() {
$('.js_floats_only').each(function() {
// Store starting value in data-value attribute.
$(this).data('value', this.value);
});
});
$(document).on('keyup', '.js_floats_only', function() {
var val = this.value;
if ( val == '-' ) {
// Allow starting with '-' symbol.
return;
} else {
if ( isNaN(val) ) {
// If value is not a number put back previous valid value.
this.value = $(this).data('value');
} else {
// Value is valid, store it inside data-value attribute.
$(this).data('value', val);
}
}
});
For simple cases and without hardcoding some html instructions would fit that pretty enough
<input type="number" step="0.01"/>
$('.number').keypress(function(event){
if($.browser.mozilla == true){
if (event.which == 8 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 9 || event.keyCode == 16 || event.keyCode == 46){
return true;
}
}
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
This works in all browsers.
<input type="text" data-textboxtype="numeric" />
<script>
$(document).on('keydown', '[data-textboxtype="numeric"]', function (e) {
// Allow: backspace, delete, tab, escape, enter and . and -
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190, 109, 189]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return true;
}
// 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();
return false;
}
return true;
});
</script>
Below Code I am allowing only Digits and Dot symbol.
ASCII characters number starts in 47 and ends with 58 and dot value is 190.
$("#Experince").keyup(function (event) {
debugger
if ((event.which > 47
&& event.which < 58) ||event.which== 190) {
if ($("#Experince").val().length > 3) {
}
} // prevent if not number/dot
else {
$("#Experince").val($("#Experince").val().slice(0, -1))
}
});