I have the following jQuery function that dynamically creates 5 collapsibles (inside a collapsible):
$(function() {
var key, value;
var Storage = 5
// loop through local storage
for (var i = 0; i < Storage; i++) {
// retrieve the key
key = i;
// set the field from the key
value = "Medicine" + i.toString();
//$("#medListDiv").show();
var text = '<div data-role="collapsible" data-collapsed="true" data-iconpos="right">' + '<h2>' + value + '</h2>' + '<input id="number' + i.toString() + '" type="text" placeholder="Quantity" />' + '<textarea cols="40" rows="4" placeholder="Type any directions written on your prescription for the above medicine." ></textarea></div>';
$("#medListDiv div:first").append(text);
}
$('#medListDiv').find('div[data-role=collapsible]').collapsible();
$('#medListDiv').trigger("create");
});
The code above sets a different id to each textbox (notice '<input id="number' + i.toString() + '" type="text" placeholder="Quantity" />').
My issue now is that I want these textboxes to only accept NUMBERS (whole digits only - no decimals) so I came up (found) with the following function that works perfectly when a "static" id is given:
$("#number0").on('keypress', function(ev) {
var keyCode = window.event ? ev.keyCode : ev.which;
//codes for 0-9
if (keyCode < 48 || keyCode > 57) {
//codes for backspace, delete, enter
if (keyCode != 0 && keyCode != 8 && keyCode != 13 && !ev.ctrlKey) {
ev.preventDefault();
}
}
});
I've been trying to make this function take any id depending on which textbox the users selects.
This Fiddle I made only shows 5 collapsibles but my original program takes user inputs and the number of medicines can vary. Notice that the first Quantity textbox wont allow any letters. I would like all the Quantity textboxes to behave the same way.
I have also tried a different function, adding var qtyID = $(this).attr(i); so removes any inputs that arent numbers, but it doesn't seem to do the work.
$(document).ready(function () {
var qtyID = $(this).attr(i);
$("#number" + qtyID).keypress(function (e) {
var value = $(this).val();
value = value.replace(/[^0-9]+/g, '');
$(this).val(value);
});
});
I have also tried placing the whole function inside the main function, but didn't help at all.
Basically all I want is to be able to get the dynamically created id from those textboxes so I can call a little function on them, but regarless of the countless examples I saw online on how to do this, I can't manage to get it working.
Any suggestions will be greatly appreciated.
Your problem is your only calling the function on your first quantity input. Instead of selecting the input by ID select it by class.
Add a number class to each input.
var text = '<div data-role="collapsible" data-collapsed="true" data-iconpos="right">' + '<h2>' + value + '</h2>' + '<input id="number' + i.toString() + '" class="number" type="text" placeholder="Quantity" />' + '<textarea cols="40" rows="4" placeholder="Type any directions written on your prescription for the above medicine." ></textarea></div>';
Then call your function on the class instead of the id Which applies to all your quantity inputs and not just the first one.
$(".number").on('keypress', function(ev) {
var keyCode = window.event ? ev.keyCode : ev.which;
//codes for 0-9
if (keyCode < 48 || keyCode > 57) {
//codes for backspace, delete, enter
if (keyCode != 0 && keyCode != 8 && keyCode != 13 && !ev.ctrlKey) {
ev.preventDefault();
}
}
});
http://jsfiddle.net/PU4UC/1/
Event delegation:
$('#medListDiv').on('keypress', '#number0', function(ev) {
You're handler is being bound at run-time and doesn't know about these dynamically created elements. Bind to an element that does exist at run.
Try This:
JQuery:
$(document).ready(function () {
$('body').on('keydown', ".number", function (event) {
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: 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();
}
}
});
});
HTML:
<td><input type=text id=Qty_' + ID + ' class="number"/></td>'
Related
I'm trying to achieve in the input box user can enter only numbers and the date format should be YY/MM/DD.
In the following example I can enter only numbers using replace method.
I want to achieve using the same method when user keyup the numbers format should be YY/MM/DD.
Please drop a comment for more clarification
$(document).on("keyup", "input", function() {
$(this).val($(this).val().replace(/[^0-9\/]/g, ''));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="form-control" placeholder="YY/MM/DD">
Please follow this.
JS
jQuery.fn.ForceNumericOnly =
function()
{
return this.each(function()
{
$(this).keydown(function(e)
{
var key = e.charCode || e.keyCode || 0;
// allow backspace, tab, delete, enter, arrows, numbers and keypad numbers ONLY
// home, end, period, and numpad decimal
return (
key == 8 ||
key == 9 ||
key == 13 ||
key == 46 ||
key == 110 ||
key == 190 ||
(key >= 35 && key <= 40) ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
});
});
};
$(document).ready(function() {
$("#datePicker").ForceNumericOnly();
$('#datePicker').keyup(function(){
let val = $(this).val()
if(val.length==2)
{
val = val+'/'
$(this).val(val)
}
else if (val.length==5)
{
val = val+'/'
$(this).val(val)
}
})
});
HTML
<input id="datePicker" type="text" maxlength="8">
I want to allow only numbers and decimal in a inputtext field.
If I use my code in a keypress event it works fine(return false when alphabets are entered), but when i use it with keyup it is not.
My code:
function OnKeyPress(e,DivID) {
if ( e.which != 8 && e.which != 0 && e.which != 13 && e.which != 190 && (e.which < 48 || e.which > 57)) {
return false;
// event.preventDefault();
}
var val = j$('[id$='+DivID+']').val();
if(DivID == 'ProximityCPPercentage')
{
var x = event.which || event.keyCode;
if(val.indexOf('.') >= 0 && e.which == 46)
return false;
else if(e.which == 46 && val.length == 3)
return false;
if(val.indexOf('.') == 0)
val = '0' + val;
if(e.which != 46)
{
strval = val + String.fromCharCode(x);
var re = /^((.|0|[1-9]\d?)(\.\d{1})?|100(\.0?)?)$/;
if(!re.test(strval))
return false;
}
}
else if(val.indexOf('.') >= 0)
{
var reg =/^(\d{0,4}\.?(\d{0,1})|\d{0,6})?$/gm;
if(!reg.test(val))
{
j$('[id$='+DivID+']').val(val.substring(0, val.length - 1));
}
}
else if(e.which != 190 )
{
if(val.length > 5)
return false;
}
}
If I use this function in onkeypress attribute of input field it is not allowing alphabets but when i use in onkeyup it does allows the alphabets.
Ok, I created a simple fiddle with an explanation of what is happening for you https://jsfiddle.net/gb0kwom0/3/
On key down, will capture the event before a value is set in the input (result: alert fire then nothing in input value), see this example.
<input type="text" onkeypress="return onPress()">
<script>
function onPress(){alert(); return false;}
</script>
On key up, will capture the event after a value is set in the input (result: value set then alert will fire), see this example.
<input type="text" onkeyup="return onUp()">
<script>
function onUp(){alert(); return false;}
</script>
So to solve your issue onKeyUp you will need to reset the value.
The result will be: will capture the event after a value is set in the input then reset the value back to empty, see this example.
note: this example is just to show the difference and should not be used, it will reset the whole value back to nothing
<input type="text" onkeyup="onUp2(this)">
<script>
function onUp2(obj){alert(); obj.value='';}
</script>
this method is not ideal and will take a lot more code to get working, it is why you should continue to use onkeypress instead
I have a simple script with simple math function. I want user to insert only numbers. How can I do it in the code? Or even better - how can I prevent the input of non-numeric characters?
$('form').submit(
function (e) {
e.preventDefault();
$('#result').text("Result is " + parseInt($('#var1').val()) / 2 + " days");
});
http://jsfiddle.net/eWXUT/1/
you can check the input thru this:
$('#var1').keypress(function(event) {
var code = (event.keyCode ? event.keyCode : event.which);
if (!(
(code >= 48 && code <= 57) //numbers
|| (code == 46) //period
)
|| (code == 46 && $(this).val().indexOf('.') != -1)
)
event.preventDefault();
});
or with jquery:
$('#val1').change(function() {
$(this).val($(this).val().match(/\d*\.?\d+/));
});
try removing non-integer values on key press/up/down - here is a live example
$('#var1').on('keypress keydown keyup', function(){
$(this).val($(this).val().replace(/([^\d]+)/, ''));
});
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 would like to show an alert on keyup event but only if the key was a letter or a number, not for shift,tab etc.
<input type='text' id='hi />
or for any key except for tab, shift, ctrl, enter
anybody knows how ?
You will have to attach an "keyup" event to the textbox and inside the event check for the keycodes you want:
$("#hi").bind("keyup", function(e) {
//on letter number
if (e.which <= 90 && e.which >= 48)
{
alert('hello');
}
});
If you want to check which character was typed, keyup is the wrong event. Only the keypress event can reliably tell you anything about the character typed. You can do it as follows:
$("#hi").keypress(function(e) {
var charTyped = String.fromCharCode(e.which);
if (/[a-z\d]/i.test(charTyped)) {
alert("Letter or number typed: " + charTyped);
}
});
This appended code accounts for numbers, characters, and digits from the numpad:
document.querySelector(selector).addEventListener('keypress', function() {
if (e.which <= 90 && e.which >= 48 || e.which >= 96 && e.which <= 105) {
alert('keycode ' + e.which + ' triggered this event');
//do whatever
}
});
That's what the onkeypress event is for, it only fires if you press a key that produces a value. MDN Docs.
I never liked the key code validation. My approach was to see if the input have text (any character), confirming that the user is entering text and no other characters.
$('#input').on('keyup', function() {
var words = $(this).val();
// if input is empty, remove the word count data and return
if(!words.length) {
$(this).removeData('wcount');
return true;
}
// if word count data equals the count of the input, return
if(typeof $(this).data('wcount') !== "undefined" && ($(this).data('wcount') == words.length)){
return true;
}
// update or initialize the word count data
$(this).data('wcount', words.length);
console.log('user tiped ' + words);
// do you stuff...
});
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input type="text" name="input" id="input">
</body>
</html>
You can check if the key code is between the range of characters you want to allow.
<input id="textbox" type='text' id='hi' />
$("#textbox").keypress(function (e){
if (e.which <= 90 && e.which >= 48)
{
alert('Letter or number click');
}
});
<input type="text" id="hi" onkeypress="keyPress()" />
function keyPress(e){
var key, x = e || window.event; key = (x.keyCode || x.which);
if(key <= 90 && key >= 48){
alert("Key pressed");
}
}