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>'
i have a input textbox in html and i want to allow the user just 'Y' or 'N' and if he tries to enter any other character then it should show an alert dialog box. so can anyone help me into dis??
jQuery version
$('input').keypress( function( e ){
$(this).val('');
var code = e.which || e.keyCode ;
if ( !( code == 89 || code == 121 ||
code == 78 || code == 110 ) ){
alert('you entered wrong key');
e.preventDefault();
}
});
check it on jsfiddle http://jsfiddle.net/TTgKF/
inline javascript version
<input id="keypress" onkeypress="return allowYN( this, event );" />
and allowYN define as
function allowYN( el, event) {
event = event || window.event;
var charCode = (event.which) ? event.which : event.keyCode;
el.value = '';
isYN = (charCode == 89 || charCode == 121 ||
charCode == 78 || charCode ==110 );
if ( !isYN ) {
alert('you entered wrong key');
}
return isYN;
}
You can add exception for Delete key (46), Backspace key (8) ..
Assuming you're able to get the HTML element by ID, this would check the #myInput element and only accept Y or N.
if ((document.getElementById('myInput').value == 'Y') ||
(document.getElementById('myInput').value == 'N')) {
// Do stuff if it's correct.
} else {
alert("You're doing it wrong!");
}
As previously noted, the best option is to use radio buttons:
<input type="radio" name="yn" value="Y">Y<br>
<input type="radio" name="yn" value="N">N<br>
Then either set one as selected or check on submit that one is selected. Alternatively, you can use scripted input elements, but it is not sensible:
<script>
function validateYN(element) {
var errNode = document.getElementById(element.id + '_err');
if(/^[YN]$/.test(element.value)) {
errNode.innerHTML = '';
} else {
errNode.innerHTML = "You must enter Y or N";
}
}
</script>
Please enter Y or N: <input name="foo" id="foo" onchange="validateYN(this);"
onblur="validateYN(this);">
<span id="foo_err"></span>
you could also try this
$("input").live('keypress', function(e) {
if!( code == 89 || code == 121 ||
code == 78 || code == 110 ) ) {
e.preventDefault();
}
else //your code
<html>
<head>
<script type="text/javascript">
function keyPressed(evt)
{
var theEvent = evt || window.event;
var k = theEvent.keyCode || theEvent.which;
if(k == 89 || k == 78 || k == 8 || k == 46)
return true;
else{
alert("Your Message");
evt.preventDefault();
return false;
}
}
</script>
</head>
<body>
<input type="text" onkeydown="keyPressed(event)" />
</body>
</html>
I'm trying to use Javascript to make a text box that contains some read-only text at the beginning of the text box and then allows editing following the read-only text. How can I do this in Javascript/jquery?
Here's an attempt:
var readOnlyLength = $('#field').val().length;
$('#output').text(readOnlyLength);
$('#field').on('keypress, keydown', function(event) {
var $field = $(this);
$('#output').text(event.which + '-' + this.selectionStart);
if ((event.which != 37 && (event.which != 39)) &&
((this.selectionStart < readOnlyLength) ||
((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input id="field" type="text" value="CAN'T TOUCH THIS!" size="50" />
<div id="output">
</div>
This disables keys other than the left and right arrows for the read-only part. It also disables the backspace key when just at the end of the read-only part.
From what I've read, this won't work on IE <= 8.
Here it is in plain JavaScript (no JQuery):
function makeInitialTextReadOnly(input) {
var readOnlyLength = input.value.length;
field.addEventListener('keydown', function(event) {
var which = event.which;
if (((which == 8) && (input.selectionStart <= readOnlyLength)) ||
((which == 46) && (input.selectionStart < readOnlyLength))) {
event.preventDefault();
}
});
field.addEventListener('keypress', function(event) {
var which = event.which;
if ((event.which != 0) && (input.selectionStart < readOnlyLength)) {
event.preventDefault();
}
});
}
makeInitialTextReadOnly(document.getElementById('field'));
<input id="field" type="text" value="CAN'T TOUCH THIS!" size="50" />
here is some thoughts
roughly a solution with jquery
html
<input type="text" id='myinput' value ="my text">
jquery
var orginal_text = $('#myinput').val();
var regular_expression = '/^' + orginal_text +'/' ;
$('#myinput').keyup(function(){
var current_text = $('#myinput').val();
if(current_text.match('^' + orginal_text +'') == null){
$('#myinput').val(orginal_text + ' ' +current_text )
}
})
http://jsfiddle.net/e5EDY/
with css
html
<input type="text" id='my_sticky_text' value ="my text" readonly='readonly'>
<input type="text" id='myinput' value ="my text">
css
#my_sticky_text{
position:absolute;
left : 0px;
}
#myinput{
position:absolute;
left : 50px;
border-left:none;
}
http://jsfiddle.net/kaf4j/
combination to retrieve the value
html
<input type="text" id='my_sticky_text' value ="my text" readonly='readonly'>
<input type="text" id='myinput' value ="my text">
<br>
<hr>
<button id='getval'>get value</button>
css
#my_sticky_text{
position:absolute;
left : 0px;
}
#myinput{
position:absolute;
left : 50px;
border-left:none;
}
jquery
$('#getval').click(function(){
var sticky_text = $('#my_sticky_text').val();
var user_text = $('#myinput').val();
alert (sticky_text + ' ' + user_text)
})
http://jsfiddle.net/YsNMQ/
what do we get from all this ?!.. simply you cant acomplish what you want in a nice way .. and i cant imagine a situation where i want to do so .
alternatives
1 - in the text-field label put the constant text .
2 - when the user submits the form capture the value of the text-field and add your text to it .
3- add a help note to the user that this input should be as follows (eg : mytext-yourtext)
Below is a modified version of John S's answer to prevent cut/paste operations (e.g. via right-click):
function makeInitialTextReadOnly(input) {
var readOnlyLength = input.value.length;
input.addEventListener('keydown', function(event) {
var which = event.which;
if (((which == 8) && (input.selectionStart <= readOnlyLength))
|| ((which == 46) && (input.selectionStart < readOnlyLength))) {
event.preventDefault();
}
});
input.addEventListener('keypress', function(event) {
var which = event.which;
if ((event.which != 0) && (input.selectionStart < readOnlyLength)) {
event.preventDefault();
}
});
input.addEventListener('cut', function(event) {
if (input.selectionStart < readOnlyLength) {
event.preventDefault();
}
});
input.addEventListener('paste', function(event) {
if (input.selectionStart < readOnlyLength) {
event.preventDefault();
}
});
}
makeInitialTextReadOnly(document.getElementById('field'));
Fiddle: http://jsfiddle.net/p0jyktvu/3/
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))
}
});