Automatic colon in time field in form - javascript

I have following requirement, in time field of form should add colon automatically on fly if not key manually in this format hh:mm:ss
I have below code and it works fine for fulling automatic, but if user key colon manually it is adding two colon like hh::m:ss
Can someone help with this issue?
JSP:
<b:form-group label="${runtime}" labelFor="runtime" cssLabel="col-sm-2" cssBody="col-sm-2" cssClass="required">
<form:input path="runTime" cssClass="form-control" required="required" maxlength="8"/>
<form:errors path="runTime" cssClass="validate-error"/>
</b:form-group>
JS:
$('#runTime').on('keydown', function(e) {
if(e.keyCode != 8 && (this.value.length === 2 || this.value.length === 5)) {
this.value += ":";
}
});
Update Answer
We have to add extra check before collapse with chiliNUT answer, else select all and hitting delete/backspace button is not working in chrome browser.
$('#runTime').on('keydown', function(e) {
//your code
if(e.keyCode != 8 && (this.value.length === 2 || this.value.length === 5)) {
this.value += ":";
}
//collapse double colons
if(this.value.endsWith("::")) {
this.value=this.value.replace(/:+/g,":");
}
});

Collapse double colons after keydown
$('#runTime').on('keydown', function(e) {
//your code
if(e.keyCode != 8 && (this.value.length === 2 || this.value.length === 5)) {
this.value += ":";
}
//collapse double colons
this.value=this.value.replace(/:+/g,":");
});
That last line will look at the string, then take any instance of 1 or more colons (contiguous colons? :-)) and turn it into a single colon

Related

how to restrict user input to only allow 0-3 with jquery? [duplicate]

I am new to jQuery and little bit confused on how to get only numbers from 1 to 5 in an input box. The following is my code:
HTML
<div id="errmsg"></div>
<input type="text" id="number" maxlength="1"/>
SCRIPT
$(document).ready(function(e) {
$('#number').keydown(function(e){
if (e.which != 8 && e.which != 0 && (e.which < 49 || e.which > 53)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
else if (e.which == 48 || e.which < 48 || e.which > 53) {
//display error message
$("#errmsg").html("5 Only").show().fadeOut("slow");
return false;
}
})
})
</script>
When the user enters any amount in the input box, if he inputs any character then error message "Digits Only" will be shown. If he enters number more than 5 then error "only 5" message will be shown.
Try This
$(document).ready(function() {
$("#number").keydown(function(event) {
console.log(event.keyCode);
if ( $.inArray(event.keyCode,[49,50,51,52,53]) !== -1)
{
alert("allow");
}
else {
alert("not allow");
}
});
});
FIDDLE
I appreciate you've already accepted an answer, but for what it's worth, I think this is a more user-friendly solution: JSFiddle
It handles control characters (such as Del, Backspace, Tab and Enter) and numbers entered through the numeric keypad. It also meets your requirement of having separate error messages for non-numeric characters and numbers > 5.
$(document).ready(function() {
$("#number").on('keyup', function(event) {
var entered = $(this).val(),
content = parseInt(entered,10);
if (entered !== '' && isNaN(content)) {
$('#errorMsg').text('Digits only');
$(this).val('');
} else if (content > 5) {
$('#errorMsg').text('Only 5');
$(this).val('');
} else {
$('#errorMsg').text('Okay');
}
});
});
However, unlike the other solution, it doesn't prevent the user from entering invalid data, but will retrospective delete the character after it has been entered. This may or may not meet your expectations.

jQuery restrict input range

I have following jQuery script implemented which suppose to restrict input in input form.
<script language="JavaScript">
var inputPlz = $j( "span#spanvertragsnehmer_plz input.plz" );
function attachEventHandlerToInputNumber(input)
{
input.on("keypress", function(key)
{
if ((key.which != 8 && key.which != 0 && (key.which < 48 || key.which > 57)) || inputPlz.val().length > 4)
{
return false;
}
});
}
attachEventHandlerToInputNumber(inputPlz);
</script>
In the following code I can restrict the input but once it goes to 5 digit number I can't edit the number using backspace anymore. Is there anything I missing here ?? Thank you.
This statement || inputPlz.val().length > 4 causes the return false; line to execute whenever the input length is 5+, no matter what key is pressed. Backspace is a key like any other thus you cannot backspace after 5+ digits.
If you want to allow backspaces once 5+ digits have been entered you could change that segment to || (inputPlz.val().length > 4 && key.which != 8))

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);

JQUERY to filter input in a textfield

I am a newbie to jquery and javascript so this may be a silly question
I have a textfield and i would like to filter the input
so it will only let the usesr enter in [A-Z] chacters and also if the length of [A-Z] has reached 3 it then also disables the user from entereing any more characters
You need a function that "monitors" the input field. Something like:
$('#yourfield').change(function() {
$val = $(this).val();
if($val.length() > 2) $(this).attr('disabled', true)
// so on, just to give you some ideas
});
http://jsfiddle.net/GLXuv/7/
$('#sexyInput').keyup(function() {
$(this).val($(this).val().replace(/[^A-Za-z]/g, ''));
if($(this).val().length >= 3) $(this).prop('disabled', true);
});​
There are two ways an input form can be populated by a user:
User types in the form.
User pastes in the form.
This requires binding two separate events:
$('.numbers-only').keypress(function(e) {
// Allow only keys [A-Za-z] and enter
if (e.which !== 13 && ((e.which < 65 || e.which > 90) && (e.which < 97 || e.which > 122)) ) {
e.preventDefault();
}
}).bind('paste', function() {
var el = this;
setTimeout(function() {
// replace anything that isn't a number with ''
$(el).val($(el).val().replace(/[^A-Za-z]/g, ''));
}, 100);
});

How can I restrict number of character input in a field with javascript or jquery?

I wrote a validation code for an input text field, which will take only numbers and some control keys. I took the help from stackoverclow :), So I am here again to take the help. My validation code is
$("#txtLevel1Year").keydown(function(event)
{
// Allow only backspace,delete,left arrow,right arraow and Tab
if ( event.keyCode == 46
|| event.keyCode == 8
|| event.keyCode == 37
|| event.keyCode == 39
|| event.keyCode == 9)
{
// 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();
}
}
});
Now let me tell you what I am looking for, first, I want to restrict this field to take exactly 4 digits.not less not more, the second one is about optimization.
The text field(s) where I want this validation to work is(are)
<asp:TextBox runat="server" ID="txtLevel1Year" Width="50px" TabIndex="13"></asp:TextBox>
<asp:TextBox runat="server" ID="txtLevel2Year" Width="50px" TabIndex="17"></asp:TextBox>
<asp:TextBox runat="server" ID="txtLevel3Year" Width="50px" TabIndex="21"></asp:TextBox>
<asp:TextBox runat="server" ID="txtLevel4Year" Width="50px" TabIndex="25"></asp:TextBox>
Here I can repeat the the validation code 4 times to make this work by grabing four different ids though the validation is exactly same. Can I do anything which can remove this repeatation? If My problem isw not clear to you, please let me know.
thanx all of you in advance.
This is the edited part of this question I have achieved the goal of optimazation by creatinf a CSS class and call it in the div where I place all the year text boxes. But My limit to make it exactly 4 digits yet to be solved. please help me.
I assume that your validation works. The trick will be to add a class for all textbox. Say the class name is
.validateTB
Then modify your script as follows
$(".validateTB").keydown(function(event)
{
// Allow only backspace,delete,left arrow,right arraow and Tab
if ( event.keyCode == 46
|| event.keyCode == 8
|| event.keyCode == 37
|| event.keyCode == 39
|| event.keyCode == 9)
{
// 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();
}
}
});
Note that only selector is changed in the script.
Remember that you can set <input maxlength="4"> in HTML as an easy solution to the half of the problem. However, this only prevents browser user from entering more than 4 characters, but you can avoid it programatically, by calling some JS function that sets longer value.
Try this: (no blinking, and no copy paste allowed):
$(".validate").keyup(function(event) {
var val = $(this).val();
if (val.length > 5) {
val = val.substring(0, 5);
$(this).val(val);
return false;
}
}).keypress(function(event) {
if ($(this).val().length > 4) {
return false;
}
});
http://jsfiddle.net/xEMzx/
Ok, first of to have your validation code to all the four fields you can use a class selector (after deining a calss for all your elements):
<asp:TextBox runat="server" class='validate'
$(".validate").keydown(function(event)
to check for length you could use a keyup event (which in my experience is better for this task)
$(".validate").keyup(function(event){
var val = $(this).val();
if (val.length > 4){
alert ("Max length is 4");
val = val.substring(0, val.length - 1);
$(this).val(val);
$(this).focus();
return false;
}
});
fiddle here: http://jsfiddle.net/a5BJX/

Categories

Resources