I am using following javascript code to autopopulate slashes and colons in a date field
Javascript
var $dateField = jQuery('input[name='dateFieldId']');
//Bind keyup/keydown to the input
$dateField.bind('keyup', 'keydown', function (e) {
// if backspace, do nothing:
var thisVal;
var appender = '';
if (e.which !== 8) {
var numChars = $dateField.val().length;
// insert '/' after 2nd and 5th character is entered
if (numChars === 2 || numChars === 5) {
appender = '/';
}
// insert whitespace after 10th character is entered
else if (numChars === 10) {
appender = ' ';
}
// insert ':' after 13th character is entered
else if (numChars === 13) {
appender = ':';
}
}
thisVal = $dateField.val() + appender;
$dateField.val(thisVal);
});
HTML
<form:input size="26" type="text" class="form-control" name="dateFieldId" id="dateFieldId" path="dateFieldId" value="" placeholder="dd/mm/yyyy hh:mm" maxlength="16" />
This is working fine on latest browsers on desktops. But its failing in old version of chrome browsers and chrome/firefox on android. One issue is that when key is pressed in datefield the focus is lost sometimes. Another is that along with the slash it adds the existing value again
For example when I type '28', instead of having '28/' which is my expected it adds 28 again after filling the slash which results in '28/280' as shown below
If anyone have encountered this please let me know. I was referring following post to do this
What's the best way to automatically insert slashes '/' in date fields
Related
I have a requirement to handle the input of up-to four scanners. These scanners can read bar-codes concurrently. Depending on their configured prefix, I need to load the bar-code in the correct text-box on my web page.
Assuming the scanners will be prefixed with 1, 2, 3, 4. Here is my code -
<input type="text" id="barcode1" />
<input type="text" id="barcode2" />
<input type="text" id="barcode3" />
<input type="text" id="barcode4" />
Above text boxes may/may not have the focus, hence using addEventListener for keypress below
<script>
var barcodewithPrefix = "";
document.addEventListener("keypress", function(e) {
if (e.keyCode != 13) {
barcodewithPrefix += e.key;
}
else {
var prefix = barcodewithPrefix.substring(0, 1);
var barcode = barcodewithPrefix.substring(1, barcodewithPrefix.length); //remove the prefix and get the actual barcode
//display in correct text box
if (prefix == "1") {
document.querySelector("#barcode1").value = barcode;
}
else if (prefix == "2") {
document.querySelector("#barcode2").value = barcode;
}
else if (prefix == "3") {
document.querySelector("#barcode3").value = barcode;
}
else{
document.querySelector("#barcode4").value = barcode;
}
barcodewithPrefix = ""; //clear for next input
}
e.preventDefault();
});
</script>
This code is working fine for one scanner as well as for keyboard input.
However, it does not run correctly if there is more than one scanner and are used concurrently. The bar-codes digits get all jumbled up and doesn't appear correctly in their respective text-box.
I understand this is expected - looking at the code where each input char is interpreted with a keypress event.
Can anyone please guide how can I make it work. Are there any workarounds to tackle it?
Thank you!
I have a phone number input that I am trying to get the dashes to appear in the number as the user types.
I am wanting the number to appear as 555-555-5555.
The function works for the most part, but the dashes aren't entered until after the whole number is entered. I am using the keyup function, which I thought would solve this, but no luck.
Does anyone have any recommendations as to what I have to do to get the dashes to be entered as the user types in the digits?
$('#phone').keyup(function() {
$(this).val($(this).val().replace(/(\d{3})\-?(\d{3})\-?(\d{4})/,'$1-$2-$3'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<label class="contact-label">Phone Number:</label>
<input type="tel" class="contact_input" name="phone" id="phone">
</div>
I modified your code slightly to produce something that I think is a little easier to read, but still does the job.
I just evaluated the length of the <input /> tag's value on each .keyup() event and then augmented the value accordingly. Take a look at the snippet below:
--UPDATE--
After comments regarding backspacing issues I added a couple lines of code that seem to fix the issue:
First I checked for either backspace or delete .keyup() events to prevent the formatting code from interfering with correcting errors in the number.
I also added a few checks, and a global formatFlag variable to ensure that if the user backspaces to an awkward index like 3 or 6(where hyphens would normally be added), that formatting would resume as normal on the next .keyup() event.
let formatFlag = false;
$(function(){
$('#phone').keyup(function(evt) {
let modifiedValue = $(this).val().replace(/-/g, "");
if(evt.keyCode == 8 || evt.keyCode == 46) { //8 == backspace; 46 == delete
//Checks whether the user backspaced to a hyphen index
if(modifiedValue.length === 3 || modifiedValue.length === 6) {
//Checks whether there is already a hyphen
if($(this).val().charAt($(this).val().length - 1) !== '-') {
formatFlag = true; //Sets the format flag so that hyphen is appended on next keyup()
} else {
return false; //Hyphen already present, no formatting necessary
}
} else {
formatFlag = false;
}
return false; //Return if backspace or delete is pressed to avoid awkward formatting
}
if(!!formatFlag) {
// This re-formats the number after the formatFlag has been set,
// appending a hyphen to the second last position in the string
$(this).val($(this).val().slice(0, $(this).val().length - 1) + '-' +
$(this).val().slice($(this).val().length - 1));
formatFlag = false; //Reset the formatFlag
}
if(modifiedValue.length % 3 == 0) {
if(modifiedValue.length === 0 || modifiedValue.length >= 9){
return false;
} else {
$(this).val($(this).val() + '-');
return;
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<label class="contact-label">Phone Number:</label>
<input type="tel" class="contact_input" name="phone" id="phone" />
</div>
I am validating user input where it should accept only 6 digits or OB followed by 8 digits only.
It works very fine for digits but when I enter any alphabet (other than O) for first time it shows "undefined" in the input text box. How to overcome this? I have initialize all variables and tried changing regular expression(/[OB0-9]*/) also but nothing is working.
Here is my jsp code with RegEx:
<input type="text" value="<c:out value='${bookingPathView.extraAANumber}'/>" name="businessExtrAA" id="enterPassengerDetailsForm.businessExtrAA" size="17" maxlength="10" pattern="[OB0-9]*" class="forceWidth-phone forceWidth6" />
Here is my Javascript code
var keepBusinessExtraMaxLength = function () {
var input = [];
jQuery("#enterPassengerDetailsForm\\.businessExtrAA").each(function(i) {
input[i]=this.defaultValue;
jQuery(this).data("idx",i);
});
jQuery("#enterPassengerDetailsForm\\.businessExtrAA").on("keyup", function (e) {
var field = jQuery(this);
var val=this.value;
var maxLength=isNaN(jQuery(field).val()) ? Number(jQuery(field).attr("maxlength")) : 6;
var thisIndex=jQuery(field).data("idx");
if (this.validity && this.validity.badInput || jQuery(field).is(":invalid") ) {
this.value = input[jQuery(thisIndex)];
return;
}
if (val.length > maxLength) {
val=val.slice(0, maxLength);
jQuery(field).val(val);
}
input[jQuery(thisIndex)]=val;
});
}
Your Regex seems to be matching only the characters , O, B and other numbers...
To make it match
6 digits or OB followed by 8 digits only
You can use this regex: ^(?:[0-9]{6}|OB[0-9]{8})$
Demonstration: http://www.regexpal.com/?fam=96586
I have a straight forward classic ASP page that uses a where the user can enter any standard keyboard key plus the Enter key (and even special ALT nnn values if they so desire)
My clarification is that I need to display an accurate character count back to the user on each ONKEYUP. So I need to know if the ENTER key has been pressed (/n) which needs to be counted as 2 chars as well as 8 other chars such as Tilde, Caret Left curly bracket, etc. which also count as 2 characters. Finally I need to validate each ONKEYUP char to ensure that they will be valid SMS chars, if not they need to be replaced in the TextArea with and Underscore (account as 1 char only)
So what I need to do is to be able to validate each character on the ONKEYUP remembering that a char could be inserted anywhere in the TextArea, an existing char could be deleted from the TextArea or parts of or the entire text could be pasted at any time
The current HTML code is as follows:
Enter your message - Characters left
<input type="text" name="chl" value="<%=Cclen%>" size=3 diabled readonly>
<br />
<textarea id="SMSmsg" name="SMSmessage" MAXLENGTH="600" rows=5 cols=35 onKeyUp="textCounter
(this)"></textarea>
<input type="text" name="chl" value="<%=Cclen%>" size=3 diabled readonly>
<br />
<textarea id="SMSmsg" name="SMSmessage" MAXLENGTH="600" rows=5 cols=35 onKeyUp="textCounter
(this)"></textarea>
The JavaScript function testcounter is as follows:
function textCounter() {
var extra = 0;
var nextra = 0;
var msgLength = 160 - (document.gs.SMSmessage.value).length - (document.gs.SMSbot.value).length;
var index = document.gs.SMSmessage.value.indexOf('\n');
while (index != -1) {
extra += 1;
index = document.gs.SMSmessage.value.indexOf('\n', index + 1);
}
Canam = nameCounter()
if (document.gs.SMSrequest.value == 'eml') {
extra = 0
nextra = 0
chnl = 999
} else {
if (document.gs.chnl.value > 0) {
nextra = 3
}
}
document.gs.chl.value = msgLength + extra - nextra;
Camsg = textWarning();
}
function nameCounter() {
var botLength = (document.gs.SMSbot.value).length;
document.gs.chnl.value = botLength;
}
function textWarning() {
var Ccwarn = " ";
if (document.gs.chl.value < -299) {
Ccwarn = "** Error ** - Extended text too long"
} else {
if (document.gs.chl.value < 0) {
if (document.gs.chex.value == 'N') {
Ccwarn = "** Error ** - Standard text too long"
} else {
Ccwarn = "** Warning ** - Extended text - Additional charge applied"
}
}
}
document.gs.chw.value = Ccwarn;
}
Any suggestions as to how to recode the JS function much appreciated taking into account my comments on the user actions within the TextArea
OK so i have this task that im not sure how to achieve. I have a text field that is only allowing the users to enter numeric values....I am validating on keypress to make sure that only numeric numbers are allowed
That works well
My problem is that the client wants text after the numbers to say " Miles" so if the user enters 100 they see "100 Miles"
I guess for usability. Does anyone know a good technique or jquery plugin to do this
In addition to a javascript solution, you may also want to look into the HTML 5 pattern attribute for <input>. For example, in modern browsers you could do something like:
<input name="miles" pattern="^\d+\s?[Mm]iles$" required>
Which requires no javascript at all :) Here's the relevant spec.
How about this:
$('input').keypress(function(e) {
if (e.which < 48 || e.which > 57) {
// not a number
return false;
}
// gets current entered numer
var number = this.value.split(' ')[0];
// adds new number
number = '' + number + String.fromCharCode(e.which);
this.value = number + ' miles';
return false;
})
It would be easier and I think clearer to do this in some sort of tag just outside of the textbox. Have a span directly below or something then update it on your keypress.
$('#textBox').keydown(function(){
// Validation code
$('#someSpan').html($(this).val() + " Miles");
});
How about this http://jsfiddle.net/TmxSN/1/
$(function(){
var timerOutId;
$('#inp').keypress(function(e) {
var key = e.which;
clearTimeout(timerOutId);
try{
if(this.value){
this.value = $.trim(this.value.match(/\d+/g)[0]);
}
}catch(e){}
if ((key < 48 || key > 57) && !(key == 8 || key == 9 || key == 13 || key == 37 || key == 39 || key == 46) ){
return false;
}
}).keyup(function(e) {
var textBox = this;
if(this.value){
timerOutId = setTimeout(function(){
textBox.value = $.trim(textBox.value.match(/\d+/g)[0]) + " Miles";
}, 2000);
}
})
});
My problem is that the client wants text after the numbers to say "
Miles" so if the user enters 100 they see "100 Miles"
Then you can handle it in the onfocus and onblur event of your input type="text" like this.
Try this
<input type="text" min="0" max="1000" step="1" id="distance" placeholder="Enter the value in miles"/>
And Script
$(document).ready(function() {
//$("#distance").keypress(PassNumbersOnly);
$("#distance").focus(OnFocus);
$("#distance").blur(OnBlur);
});
function OnFocus() {
var $this = $(this);
if ($this.val().indexOf("Miles") != -1) {
$this.val($this.val().split(" ")[0]);
}
}
function OnBlur() {
var $this = $(this);
if ($.trim($this.val()) != "") {
$this.val($this.val() + " Miles");
}
}
Demo here: http://jsfiddle.net/naveen/EQEMr/
Tell your client that anyone with enough intelligence to use the web can understand:
<label for="distance">Distance in miles:
<input type="text" name="distance" id="distance"></label>
and that doing anything else is:
confusing for users
problematic as javascript may or may not be enabled/available
of zero practical use for the business as the value must be validated on the server anyway
the value requires additional processing at the server to remove the appended characters