Javascript check if an input is a Long or not [duplicate] - javascript

How do I limit or restrict the user to only enter a maximum of five characters in the textbox?
Below is the input field as part of my form:
<input type="text" id="sessionNo" name="sessionNum" />
Is it using something like maxSize or something like that?

maxlength:
The maximum number of characters that will be accepted as input. This can be greater that specified by SIZE , in which case the field
will scroll appropriately. The default is unlimited.
<input type="text" maxlength="2" id="sessionNo" name="sessionNum" onkeypress="return isNumberKey(event)" />
However, this may or may not be affected by your handler. You may need to use or add another handler function to test for length, as well.

The simplest way to do so:
maxlength="5"
So.. Adding this attribute to your control:
<input type="text"
id="sessionNo"
name="sessionNum"
onkeypress="return isNumberKey(event)"
maxlength="5" />

Add the following to the header:
<script language="javascript" type="text/javascript">
function limitText(limitField, limitNum) {
if (limitField.value.length > limitNum) {
limitField.value = limitField.value.substring(0, limitNum);
}
}
</script>
<input type="text" id="sessionNo" name="sessionNum" onKeyDown="limitText(this,5);"
onKeyUp="limitText(this,5);"" />

Make it simpler
<input type="text" maxlength="3" />
and use an alert to show that max chars have been used.

According to w3c, the default value for the MAXLENGTH attribute is an unlimited number. So if you don't specify the max a user could cut and paste the bible a couple of times and stick it in your form.
Even if you do specify the MAXLENGTH to a reasonable number make sure you double check the length of the submitted data on the server before processing (using something like php or asp) as it's quite easy to get around the basic MAXLENGTH restriction anyway

<input type="text" maxlength="5">
the maximum amount of letters that can be in the input is 5.

Maxlength
The maximum number of characters that will be accepted as input.
The maxlength attribute specifies the maximum number of characters allowed in the element.
Maxlength W3 schools
<form action="/action_page.php">
Username: <input type="text" name="usrname" maxlength="5"><br>
<input type="submit" value="Submit">
</form>

I always do it like this:
$(document).ready(function() {
var maxChars = $("#sessionNum");
var max_length = maxChars.attr('maxlength');
if (max_length > 0) {
maxChars.on('keyup', function(e) {
length = new Number(maxChars.val().length);
counter = max_length - length;
$("#sessionNum_counter").text(counter);
});
}
});
Input:
<input name="sessionNum" id="sessionNum" maxlength="5" type="text">
Number of chars: <span id="sessionNum_counter">5</span>

You can use
<input type = "text" maxlength="9">
or
<input type = "number" maxlength="9"> for numbers
or
<input type = "email" maxlength="9"> for email
validation will show up

<input type="number" id="xxx" name="xxx" oninput="maxLengthCheck(this)" maxlength="10">
function maxLengthCheck(object) {
if (object.value.length > object.maxLength)
object.value = object.value.slice(0, object.maxLength)
}

The following code includes a counted...
var count = 1;
do {
function count_down(obj, count){
let element = document.getElementById('count'+ count);
element.innerHTML = 80 - obj.value.length;
if(80 - obj.value.length < 5){
element.style.color = "firebrick";
}else{
element.style.color = "#333";
}
}
count++;
} while (count < 20);
.text-input {
padding: 8px 16px;
width: 50%;
margin-bottom: 5px;
margin-top: 10px;
font-size: 20px;
font-weight: 700;
font-family: Raleway;
border: 1px solid dodgerblue;
}
<p><input placeholder="Title" id="bike-input-title" onkeyup="count_down(this, 3)" maxlength="80" class="text-input" name="bikeTitle" ></p>
<span id="count3" style="float: right; font-family: Raleway; font-size:20px; font-weight:600; margin-top:-5px;">80</span><br>

Late to the party, but if you want a full proof way to restrict numbers or letters that is simply javascript and also limits length of characters:
Change the second number after .slice to set the how many characters. This has worked much better for me then maxlength.
Just Numbers:
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').slice(0, 11);
Just Letters:
oninput="this.value=this.value.replace(/[^A-Za-z\s]/g,'').slice(0,20);"
Full example:
<input type="text" name="MobileNumber" id="MobileNumber" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').slice(0, 11);"/>

Use maxlenght="number of charcters"
<input type="text" id="sessionNo" name="sessionNum" maxlenght="7" />

<input type="text" name="MobileNumber" id="MobileNumber" maxlength="10" onkeypress="checkNumber(event);" placeholder="MobileNumber">
<script>
function checkNumber(key) {
console.log(key);
var inputNumber = document.querySelector("#MobileNumber").value;
if(key.key >= 0 && key.key <= 9) {
inputNumber += key.key;
}
else {
key.preventDefault();
}
}
</script>

Related

Is there a way to limit the number of decimal characters in an input when its used as a result box?

I'm making a simple html where i make calculations based on different inputs and presenting the results in other inputs using pure js.
In the below example where i divide a / b input and return the result in c,lets say you put 633 / 33 it returns a number like this : 19.181818181818183
Is there a way to make look like 19.18 ?
Using the maxlength Attribute to the result input wont work as it limits the number of characters you can type in,not the number of characters you can send to.
<input type="text" id="input1" style="width: 100px " onkeyup='divide_numbers()'/>
<label> / </label>
<input type="text" id="input2" style="width: 100px " onkeyup='divide_numbers()'/>
<label> = </label>
<input type="text" id="result" style="width: 100px "/>
<script>
function divide_numbers() {
var first_number = parseFloat(document.getElementById("input1").value) ;
var second_number = parseFloat(document.getElementById("input2").value) ;
document.getElementById("result").value=first_number/second_number ;
}
</script>
You can use +number.toFixed(2), which will first create a string with two digits after the decimal point and then coerce it back to a number, removing unnecessary decimal digits.
function add_numbers() {
var first_number = parseFloat(document.getElementById("input1").value) ;
var second_number = parseFloat(document.getElementById("input2").value) ;
document.getElementById("result").value = +(first_number/second_number).toFixed(2);
}
<input type="text" id="input1" style="width: 100px " onkeyup='add_numbers()'/>
<label> / </label>
<input type="text" id="input2" style="width: 100px " onkeyup='add_numbers()'/>
<label> = </label>
<input type="text" id="result" style="width: 100px "/>

How to show masked character (like asterisk '*') in input type number as numbers are typed

I am using a html input type='number' field to set PIN no (no characters are allowed) but I want the characters to be masked as I type.
I am new in web development. Please help me out.
You can use like this-
<input type="password" pattern="[0-9]*" inputmode="numeric">
see details here
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/password#Setting_length_requirements
I think this helps if you want to make input type='password' accept only numbers
Solution with jQuery
$(function () {
$('#pincode').bind('keyup paste', function () {
this.value = this.value.replace(/[^0-9]/g, '');
});
$('#pincode').keyup(function () {
var text = $(this).val().trim();
$('#errorname').text(text);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post" id="sign_in_form">
<div class="form-group">
<label for="email" style="font-weight: bold; cursor: text;"><span style="color:red;">* </span>Enter PIN</label>
<input type="password" name="pincode" id="pincode" maxlength="6" inputmode="numeric">
</div>
<div id="errorname"></div>
</form>

Prevent users from entering a value greater than 2 digits in an input field

I have a HTML form field to get the month from the user.
<input type="text" placeholder="MM" size="2" name="month">
I need the field to accept only 2 digits. I tried Form validation, but it allows the user to enter more than 2 digits and then display the validation message. I don't need any validation messages for the field, but the user should be restricted to enter only 2 digits max. Is there a way we can do this using jquery?
<input type="text" placeholder="MM" size="2" name="month" maxlength="2>
The maxlength attribute;
<input type="text" placeholder="MM" size="2" maxlength="2" name="month">
It limits the amount of text you can enter by straight up not allowing you to type more.
EDIT: added snippet
The easiest is using the type='number' attribute and setting max='12':
<input type='number' max='12' min='1'>
SNIPPET
input {
width: 4ex;
padding: 0 1px;
}
input:last-of-type {
width: 6.5ex;
}
<fieldset>
<legend>Enter Date</legend>
<label>Month:</label>
<input type='number' max='12' min='1'>
<label>Day:</label>
<input type='number' max='31' min='1'>
<label>Year:</label>
<input type='number' max='3000' min='2016'>
</fieldset>
This should help you out, whenever the user presses the key down it will check the lenght and then trim the extra chars if there are any:
$("input").keydown(function() {
var value = $(this).val();
if(value.length > 2) {
value = value.substring(0, 2);
$(this).val(value);
}
});

dijit ValidationTextBox how to add minlength and maxlength

I would like to know how (with simple working example) to add maxlength and minlength to input tag generated by
dijit/form/ValidationTextBox
Example of desired output:
<input maxlength="10" minlength="2" class="dijitReset dijitInputInner" data-dojo-attach-point="textbox,focusNode" autocomplete="off" name="title" type="text" tabindex="0" id="Image-1-title-LabelValidationTextBox" aria-required="undefined" value="Title text for image Image-1" aria-invalid="false">
try this example with regex constraint
<input type="text" value="someTestString" required="true"
data-dojo-type="dijit/form/ValidationTextBox"
data-dojo-props="regExp: '[a-zA-Z0-9$%!_]{2,10}', invalidMessage: 'The value must be at least 2 character and maximum 10'" />
ValidationTextBox has the properties minLength and maxLength. They are used in the following why in a declarative manner.
<input data-dojo-type="dijit/form/ValidationTextBox"
data-dojo-props="required:true,
maxLength:5,
minLength:2"
type="text"
name="exmaple" />
Here's another solution:
registry.byId("validationTextBox").validator = function(value, constraints) {
if(value) {
return value.length >= 2 && value.length <= 10;
}
return true;
}

maxlength=5 not working if input type=number

This is frustrating!
When the input type is text and I gave maxlength as 5, it is not allowing me to enter more than 5 characters
<input type="text" maxlength="5" />
If I gave input type as number and I gave maxlength as 5, it is allowing more than 5 digits?
<input type="number" maxlength="5" pattern="[0-9]*" />
Am I missing something?
PS: This is for mobile responsive site!
Instead of maxlength use max
<input type="number" min="1" max="10000" />
Update
Small jQuery plugin
(function ($) {
$.fn.maxlength = function (length) {
return this.on('keydown', function () {
var maxlength = length || parseInt($(this).attr('maxlength'), 10) ;
if (maxlength && $(this).val().length >= maxlength) {
$(this).val($(this).val().slice(0, maxlength - 1));
}
});
};
}($));
Example
try using max...
<input type="number" max="99999" />
EDIT: Showing Validation
<form id='FormValidation'>
<input id="myNum" type="number" min="1" max="99999" />
<input type="text" maxlength="5" />
<input type="submit" />
</form>
Try adding a number greater than 99999 and hitting submit, check the updated fiddle.
This jquery could help too...
$('#myNum').keyup( function(e){
var max = $('#myNum').attr('max').length;
if ($(this).val().length >= max) {
$(this).val($(this).val().substr(0, max));
}
});
replace maxlength with max
// Max Length = 5
<input type="number" max="99999" />
// length between 1 to 5
<input type="number" min="1" max="99999" />
Updated Answer. It's so simple!
<input type="number" id="nbr"/>
<input type="text" maxlength="5" />
$(document).on('keypress','#nbr', function(e){
if($(this).val().length >= 5)
{
e.preventDefault();
}
});
And you can add a max attribute that will specify the highest possible number that you may insert
<input type="number" max="999" />
if you add both a max and a min value you can specify the range of allowed values:
<input type="number" min="1" max="999" />

Categories

Resources