Disable zero as first letter in <input> - javascript

Below code disables 0 as the first character in #foo.
However, you can bypass this by typing 123, then drag to select 123 and putting 0. (or ctrl+a on input)
Is there a way to block this scenario?
$('input#foo').keypress(function(e){
if (this.value.length == 0 && e.which == 48 ){
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="foo" />

I would handle the input, propertychange, and paste events. Then use regex to match for anything that begins with 0 and replace the current value with the value minus the leading 0.
http://jsfiddle.net/SeanWessell/5qxwpv6h/
$('input ').on('input propertychange paste', function (e) {
var val = $(this).val()
var reg = /^0/gi;
if (val.match(reg)) {
$(this).val(val.replace(reg, ''));
}
});
Bug fix reported by Kevin/Updated per recommendations of canon:
http://jsfiddle.net/SeanWessell/5qxwpv6h/2/
$('input').on('input propertychange paste', function (e) {
var reg = /^0+/gi;
if (this.value.match(reg)) {
this.value = this.value.replace(reg, '');
}
});

I think you're looking for the keydown jQuery event as opposed to the keypress event. Here's some move info on the difference between the two. Try regex to get rid of leading zeroes:
$('input#foo').keydown(function(e){
this.value = this.value.replace(/^0+/, '');
});

Here's the fixed version :
<input id="foo" />
$('input#foo').keyup(function(e){
if(this.value.substring(0,1) == "0")
{
this.value = this.value.replace(/^0+/g, '');
}
});
jsfiddle : http://jsfiddle.net/ewmb1yq9/4/

This could work:
$('input#foo').keyup(function(e) {
if((this.value+'').match(/^0/)) {
this.value = (this.value+'').replace(/^0+/g, '');
}
});
The only thing that could bother you with this solution is that zero is displayed for a second and then deleted, since we are using keyup event.
A quick demo

Accept only numeric values not prefixed by zero. Supports Ctrl + A:
var escapeKeys = [8, 46];
$('input#foo').keyup(function (e) {
if ($.inArray(e.keyCode, escapeKeys) != 0) {
if ((this.value + String.fromCharCode(e.keyCode)).match(/^[1-9][0-9]*$|^$/) != null) {
this.lastValidValue = this.value + String.fromCharCode(e.keyCode);
} else if (this.lastValidValue) {
this.value = this.lastValidValue;
} else {
this.value = "";
}
} else {
this.lastValidValue = this.value;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="foo" />

If you want to catch the changes to the input's value (including the changes made by dragging part of the text for example), you can watch the input event.
$('input#foo').on("input", function(){
alert($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="foo" />

You could add a "submit" event to validate whether it's entered or not, regardless of how it could have gotten there:
$( "form" ).submit(function( event ) {
if ( $( "input:first" ).val() != 0 ) {
$( "span" ).text( "Validated..." ).show();
return;
}
$( "span" ).text( "Not valid!" ).show().fadeOut( 1000 );
event.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<p>Type 'Anything but 0' to validate.</p>
<form action="javascript:alert( 'success!' );">
<div>
<input type="text">
<input type="submit">
</div>
</form>
<span></span>
jQuery's working is example is last on page here (https://api.jquery.com/submit/)
NOTE: The most important part will be to add the "event.preventDefault()" action, because that will keep the form from accidentally submitting.

Related

Extend function to prevent paste inside an input field

I'm currently trying to prevent typing everything instead of numbers and points inside a an input field. The problem is that pasting letter or strange things still works. So is there a way to prevent it in my function?
I could do a HTML part like onpaste="return false;" but maybe there is a better solution that uses my available function. Thanks for your help!
jQuery( document ).ready( function ( $ ) {
$( document ).on( "keypress keyup paste", "#test", function ( event ) {
let input = $( this ).val();
console.log(input);
console.log(event.which);
if ( ( event.which !== 46 || $( this ).val().indexOf( '.' ) !== -1 ) && ( event.which < 48 || event.which > 57 ) ) {
event.preventDefault();
} else if ( ( input.indexOf( '.' ) !== -1 ) && ( input.substring( input.indexOf( '.' ) ).length > 2 ) ) {
event.preventDefault();
}
} );
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="test"/>
Edit:
I also found out that the sign ^ still works too but has no event? How is this possible?
The idea is to only allow numbers with points and two decimals like 22222.22 for example.
Edit 2:
Input type number is not working because it allows more than just numbers and points.
<input type="number"/>
Somehow below code handles ctrlX, ctrlV, ^, and allows decimal input
const input = document.querySelector('input')
let old = input.value
input.addEventListener('input', function() {
if (!this.checkValidity()) {
this.value = old
} else {
old = this.value
}
})
<input type="text" pattern="\d+(\.[\d]{0,2})?"/>
For dynamically added input (by using event delegation) we could store the old attribute on the input itself
jQuery( document ).ready( function ( $ ) {
$( document ).on( "input", "input.decimals", function ( event ) {
if (!this.checkValidity()) {
this.value = this.dataset.old || ''
} else {
this.dataset.old = this.value
}
return true
})
const pattern = '\\d+(\\.[\\d]{0,2})?'
document.querySelector('div').innerHTML += `<input class="decimals" type="text" pattern="${pattern}"/>`.repeat(2)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div></div>
You can try to explicitly disable cut, copy, or paste functionality on targeted element (e.g: #txtInput element) using the snippet below:
$(document).ready(function(){
$('#txtInput').on("cut copy paste",function(e) {
e.preventDefault();
});
});
More on how to do this here: How to prevent pasting into input fields.
Have you tried the simple solution which is to use input of type number?
e.g. <input type="number" />
There is a caveat, the letter 'e' can be typed, i.e. Euler's Number

change spaces entered in input field to underscore in real time

I have an input field that should switch all spaces entered to a '_' in real time. Meaning when the user hits the spacebar in that input field a underscore is being displayed instead of a space. I am quite new to javascript/jquery so please don't judge my setTimeout-n00bidity to hard:
$( "#inputId" ).keydown(function (key){
var code = key.keyCode || key.which;
if( code == 32 ) { //Space key code
$( this ).val(
function( index, value ){
return value.substr( 0, value.length - 1 );
})
setTimeout(
function(){
$(this).val($(this).val() + "_");
}, 10
)
}
})
You may listen to the input event and then replace the spaces with underscores in the listener. This way, you don't need to have a timeout.
$("#inputId").on('input', function(key) {
var value = $(this).val();
$(this).val(value.replace(/ /g, '_'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="inputId">
No jQuery, simple solution:
var input = document.getElementById("inputId");
input.oninput = function (e) {
e.target.value = e.target.value.replace(' ', '_');
}
<input type="text" id="inputId" />
Use the keyup event rather than keydown, and simply replace all spaces with _. The keyup event runs after the value has been modified based on what the user typed, so you don't need to check the charCode.
$("#inputId").keyup(function() {
$(this).val(function(i, oldval) {
return oldval.replace(/ /g, '_');
});
});
You can use Change value of key board input
ex:
<div>
<label>Test:</label>
<input type="text" id="test">
</div>
$("#test").on("keypress", function (e) {
if (32 == e.keyCode) {
e.preventDefault();
var newString = $("#test").val() + "_";
$("#test").val(newString);
}
});
Related: jQuery: Change keyboard value when input
$( "#inputId" ).keyup(function (key){
var code = key.keyCode || key.which;
if( code == 32 ) { //Space key code
$(this).val($(this).val().replace(/ /g,"_"));
}
});

Set an input field to accept only numbers with jQuery

I have to define an input text which accepts only integer numbers.
I tried with a regular expressions but the decimal part of the value is still visible.
I used this function:
$(document).on("input","input", function(e) {
this.value = this.value.replace(/[^\d\\-]/g,'');
})
How about this one?
$('input').on('input blur paste', function(){
$(this).val($(this).val().replace(/\D/g, ''))
})
<input>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Simple and easy to use. Try it:
edited: also call in onblur event to prevent paste.
function numOnly(selector){
selector.value = selector.value.replace(/[^0-9]/g,'');
}
<input type="text" onkeyup="numOnly(this)" onblur="numOnly(this)">
You can detect on keydown if is numeric and you can check on paste event if is numeric and remove all non-numeric. This remove dot too.
Original source : keydown detect : Paste remove
This code below has been modified from the original source.
Please try:
$( "#input" ).on("paste", function() {
setTimeout(function(){
if ($('#input').val() != $('#input').val().replace(/\D/g,""))
{
$('#input').val($('#input').val().replace(/\D/g,""));
}
},10)
});
$('#firstrow').on('keydown', '#input', function(e){-1!==$.inArray(e.keyCode,[46,8,9,27,13])||/65|67|86|88/.test(e.keyCode)&&(!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/2.1.1/jquery.min.js"></script>
<div id="firstrow">
<input id="input" type="text">
</div>
Finally I solved the above issue with my requirement to type only number is
$(document).on("input", ".skilltxt", function(e) {
this.value = this.value.replace(/[^\d]/g,'');
});
$(".skilltxt").on('paste',function(e) {
if(gBrowser=='IE') {
var clipboardData, pastedData;
clipboardData = e.clipboardData || window.clipboardData;
pastedData = clipboardData.getData('Text');
}
else if((gBrowser=='Firefox')|| (gBrowser=='Chrome')){
var pastedData = (e.originalEvent || e).clipboardData.getData('text/plain');
window.document.execCommand('insertText', false, pastedData)
}
if(Math.floor(pastedData) == pastedData && $.isNumeric(pastedData)){
$(this).val($(this).val().replace(/[^\d]/g,''));
}
else{
return false;
}
});

Trying to remove non numeric characters from textbox using jQuery

I'm trying to remove a character as it's typed/keyed up to test whether it's a number or not, if it is a number, keep it, if not, remove it. It can be more than one digit. for example, I type in a "d", it should be deleted from the textbox. I then type a "1", where it should stay in the textbox. I then type a 4 and it also stays so the textbox now reads "14". Then I type "g", which should be deleted. Then I type a "5" and now the text box reads 145. This is what I have so far.
$("#txtTestNumbersOnlyRegex").keyup(function () {
$("#txtTestNumbersOnlyRegex").val(function (index, value) {
var keyPressed = value.substr(0, value.length - 1);
var regEx = new RegExp("/^5$/");
if(!regEx.test(keyPressed)) {
alert("true");
return value.substr(0, value.length - 1);
}
});
});
You might want to try this:
$("#txtTestNumbersOnlyRegex").keyup(function () {
var newValue = $(this).val().replace(/[^0-9]/g,'');
$(this).val(newValue);
});
You can try it here https://fiddle.jshell.net/aooh0gkz/
You can use regex to replace any non digits with empty space, although this will look a bit weird.
$('input').keyup(function() {
$(this).val($(this).val().replace(/\D/, ''));
});
Full snippet:
$('input').keydown(function() {
console.log($(this).val());
$(this).val($(this).val().replace(/\D/, ''));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
Or you could use input type="number" if you don't care about IE support.
You can intercept the values that are coming in and decide what to do, So it is better to have the keypress else your text gets replaced everytime and say if you are in middle of input val and you are editing caret will jump to the end in other cases
$("#txtTestNumbersOnlyRegex").keypress(function (event) {
var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
if((keyCode>=65 && keyCode<=90) || (keyCode>=97 && keyCode<=122))
return false;
else return true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=text id = txtTestNumbersOnlyRegex />

Non repeat comma

<input type="text" class="dot"> <br />
<input type="text" class="dot"> <br />
<input type="text" class="dot"> <br />
$('.dot').keydown(function(){
$(this).val($(this).val().toString().replace(/\./g, ','));
})
http://jsfiddle.net/ZtkBW/
In this example i replace dot to comma. How can i block the addition of two commas in current input?
If in input is already one comma then next should be remove.
This is a classic case of trying to solving a problem with regular expressions, and now you have two problems...
It's not clear exactly what you want, but this will stop multiple presses of the comma key. It should be a short step from here to detect the period (code 190) and do whatever you want with it instead.
$('.dot').keydown(function(e){
if (e.which == 188) {
if (this.value.indexOf(',') != -1) {
e.preventDefault();
return false;
}
}
})​;
Use the keypress event instead of the keydown event (as keydown isn't triggered by key repeat).
Look for the . and , characters, and stop the event by returning false if there already is a comma in the text.
As the event is stoppable, it occurs before the value is changed, so you need to use a timeout for replacing the period with a comma.
$('.dot').keypress(function(e){
var txt = $(this).val();
if (e.which == 46) {
if (txt.indexOf(',') != -1) {
return false;
} else {
var t = $(this);
window.setTimeout(function(){
t.val(t.val().replace('.', ','));
}, 0);
}
} else if (e.which == 44) {
return txt.indexOf(',') == -1;
}
});
Demo: http://jsfiddle.net/eAkUc/1/
$('.dot').keypress(function(e){
if( ($(this).val().indexOf(',') != -1 || $(this).val().indexOf('.') != -1) &&
(e.charCode==','.charCodeAt(0) || e.charCode=='.'.charCodeAt(0)) )
e.preventDefault();
else
$(this).val($(this).val().toString().replace(/\./g, ','));
})​;​
DEMO
If I understand what you want correctly, here's one way of doing it:
var myVal = $(this).val();
myVal[myVal.indexOf(",")] = ".";
myVal.split(",").join("");
$(this).val(myVal);

Categories

Resources