I have a text field, I am using onkeypress to check the length of the entered string. If it exceeds n number of characters it will return false and it will not accept any other character, But Here I am unable to remove the characters I don't want in thetext field. How can I remove the text here.
Try this, if you are using textarea
<textarea onkeypress="return limitlength(this, 20)" style="width: 300px; height: 90px"></textarea>
function limitlength(obj, length){
var maxlength=length
if (obj.value.length>maxlength)
obj.value=obj.value.substring(0, maxlength)
}
Use simple HTML5, no need javascript:
<input type="text" maxlength="5"/>
MDN
Check the length of the entered text in Onkeyup event. If it is greter than n then use substring to truncate first n characters and then set the new string as the value
$("#mytxt").onkeyup(function(){
var Currentlength =$(this).val().length;
var CurrentVal = $(this).val();
if(Currentlength > n)
{
$(this).val(CurrentVal.substring(0,n));
return false;
}
});
Related
I want to auto list numbers every time the user types in 3 digits. The input numbers should appear in the div automatically.
$("#lister").on("keyup", function() {
var mxlen = $(this).data("mxlen");
var input = $(this).val();
if (input.length == mxlen) { //if input==3
$('#num_list').append('<li>' + input + '</li>');
$(this).html(''); //clear input after appended
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="num_list"></div>
<input type="number" id="lister" data-mxlen="3" />
The problem with my code is that it repeats the same numbers and does not clear the input after appending.
Your code is almost there, you just need to use val('') to reset the value.
Also note that you can make the logic more robust by using slice(0, mxlen) to restrict the value to 3 characters when typing quickly, and also change the check from == to >= for the same reason.
$("#lister").on("input", function() {
let $el = $(this);
var mxlen = $el.data("mxlen");
var input = $el.val();
if (input.length >= mxlen) {
$('#num_list').append('<li>' + input.slice(0, mxlen) + '</li>');
$el.val('');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="num_list"></div>
<input type="number" id="lister" data-mxlen="3" />
One last thing to note is that characters such as - or e are valid for entry in a type="number" input field, however they are not valid for the value returned from the field. As such the length check will get inconsistent output when these characters are used.
Depending on your use case you may be better off with a standard type="text" check and manually restricting the input to numerical values.
I've walked into a strange problem. When trying to replace a dot on a number input, instead of replacing just that dot, it clears out the entire input.
$("[data-input-payment-id]").on("keyup", function(e) {
var test_value = $(this).val().replace(/\./g, "");
$(this).val(test_value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" data-input-payment-id="12">
JSFIDDLE
How do I change it so it only removes the dots?
I think (guessing) it's because you use type="number". Then digits followed by a dot, e.g. 123., isn't a valid number, and val returns blank.
You could try this instead:
$("[data-input-payment-id]").on("keyup", function(e) {
var test_value = this.value.replace(/[^\d,]/g, "");
$(this).val(test_value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-input-payment-id="12">
This uses normal text type and filters out anything but digits in the replace.
Edit:
Changed the regex to match anything but numbers and commas.
Your Keypress example gave me this idea. If you can intercept the keypress event, it is possible to check any validation before adding the actual value. This example also does not require any conditional and is able to filter any non-digit value.
$("[data-input-payment-id]").on("keypress", function(e) {
if ((this.value + e.key).match(/\D/)) {
return false;
}
});
$("[data-input-payment-id]").on("paste", function(e) {
var pasteData = (e.originalEvent.clipboardData || window.clipboardData).getData('text');
pasteData = pasteData.replace(/\D/g, '');
this.value = this.value + pasteData;
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" data-input-payment-id="12">
Allows pasting data with filtering
No specific conditionals
Can be modified for custom validation
http://jsfiddle.net/xpvt214o/511118/
I would:
Instead of the keyup event, listen to the input event. This way you can also allow pasting.
Keep a record of the previous correct value, so that you can roll back to it. This is necessary because type=number inputs will have an empty string as value as soon as the input becomes invalid (as a number). I would store that previous correct value in a data property of the input element
With the use of the property validity.stepMismatch you can know whether the current value is violating the step property of the input which by default is 1. With a step of 1, this means entering a number with a decimal separator will be considered a mismatch.
As a trailing decimal separator will not (yet) yield a fractional number, it will pass the above validation. So echo the value back into the input when all is OK: this will eliminate any trailing decimal separator that might have been keyed in.
$("[data-input-payment-id]").on("input", function (e) {
if (!this.validity.stepMismatch) {
$(this).data("lastValid", $(this).val());
};
$(this).val($(this).data("lastValid") || "");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number"data-input-payment-id="12">
Having said this, I personally am not in favour of blocking user input in this way: they might for a moment think their keyboard is broke. It is in my opinion better to allow the user to type anything and just indicate with a message next to the input that the input is not valid (until it is).
This isn't really a solution as I'd personally like to see it, but here is what I did to solve the problem at hand. I changed the JavaScript code to listen for keycode 46 (the .) and I'm returning false on the paste event listener to disable pasting a value into the input.
$("[data-input-payment-id]").on("keypress", function(e) {
var key = e.charCode ? e.charCode : e.keyCode;
if (key == 46) {
return false;
}
});
$("[data-input-payment-id]").on("paste", function(e) {
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" data-input-payment-id="12">
It works at least in Chrome and Edge.
See MDN docs on inputs of type number:
Value
A Number representing a number, or empty
If the input string cannot be converted to a proper number - such as if the string contains two dots - then accessing the .value property will return the empty string.
The .value (and val() function) will still return strings, but those strings must represent valid numbers (or be the empty string). Rather than setting the element's value unconditionally, simply check to see if the value isn't the empty string first:
$("[data-input-payment-id]").on("keyup", function(e) {
const val = $(this).val();
if (val === '') return;
var test_value = $(this).val().replace(/\./g, "");
$(this).val(test_value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" data-input-payment-id="12">
Or you might use a text input, and possibly a pattern:
$("[data-input-payment-id]").on("keyup", function(e) {
const val = $(this).val();
var test_value = $(this).val().replace(/\./g, "");
$(this).val(test_value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input data-input-payment-id="12">
<input type="submit">
</form>
<form>
<input pattern="^\d+$" data-input-payment-id="12">
<input type="submit">
</form>
$(this).val() is returning an empty string if an input with type="number" has more than one .
You can fix this, by only running the replacing the value if $(this).val() does not return an empty string.
I want aadhar number in format of xxxx-xxxx-xxxx. Text box sholud take the input in this format automatically.
While entering the input the input should automatically convert into this(xxxx-xxxx-xxxx) format.
Only numericals should be accepted.
I want mobile number in format +91(or any other country code)-9999999999(10 digit mobile number).
I have tried /^(?:\(\d{3}\)|\d{3}-)\d{3}-\d{4}$/, but its not working please help
I want aadhar number in format of xxxx-xxxx-xxxx. text box sholud take
the input in this format automatically.
One example would be to enforce input to only accept the adhaar number format
$('[data-type="adhaar-number"]').keyup(function() {
var value = $(this).val();
value = value.replace(/\D/g, "").split(/(?:([\d]{4}))/g).filter(s => s.length > 0).join("-");
$(this).val(value);
});
$('[data-type="adhaar-number"]').on("change, blur", function() {
var value = $(this).val();
var maxLength = $(this).attr("maxLength");
if (value.length != maxLength) {
$(this).addClass("highlight-error");
} else {
$(this).removeClass("highlight-error");
}
});
.highlight-error {
border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" data-type="adhaar-number" maxLength="19">
I am not interested in giving u everything, but I will point you in the right direction. Use regular expressions.
This regex will help your case but you need to put in your effort on how it must be used in your situation.
console.log(/\d{4}-\d{4}-\d{4}-\d{4}/.test('1000-1000-1000-1002'));
I have an html input type="number" field in an html page. like this:
<input type="number">
To validate the form I need to check that the length of this field is exactly 3. To do this I convert the number to String and execute the length() function.
The problem comes when the number starts with a zero. like 065
In that case the toString() method outputs a 65 with a length of 2
Do you have any idea on how to get the correct length of the number ?
I think that you would have to have your input type as text and then use JavaScript to get the length for validation. After that you could convert it to a number using the Number() function.
Change the input type to text and restrict the input with a pattern and maxlength:
<input type="text" pattern="\d*" maxlength="3">
You can solve this one of two ways:
When the user moves focus away from the field, remove the leading zeroes
In the validation, remove the leading zeroes then check the length
There is no need to convert to a number.
Removing leading zeroes when focus is lost:
function truncateNumericInput(event) {
event = event || window.event;
event.target = event.target || event.srcElement;
if (event.target.nodeName != "INPUT" || event.target.type != "number") {
return;
}
var input = event.target,
value = event.target.value;
input.value = value.indexOf(".") > -1
? value.replace(/^0{2,}/, "0")
: value.replace(/^0+/, "");
}
if (document.addEventListener) {
document.addEventListener("blur", truncateNumericInput, true);
} else {
document.attachEvent("focusout", truncateNumericInput);
}
JSFiddle: http://jsfiddle.net/67jyg1d9/
Removing leading zeroes during validation
var regex = /^0+/;
var value = input.value.replace(regex, "");
console.log(value.length <= 3)
<input type="number" name="quantity" min="0" max="999">
this takes care that only number can be entered and only till 999 that's 3 digits at max
You can solve your problem by using input type as number. You can build your logic by using overflow and underflow as shown below.
<input id="numtest" type="number" min="10" max="20" />
document.getElementById('numtest').validity.rangeOverflow
document.getElementById('numtest').validity.rangeUnderflow
or
document.getElementById('numtest').checkValidity();
rangeUnderflow: return true if value is less then min
rangeOverflow: return true if value is greater than max value.
Is there a quick javascript library or code that would only allow a user to start a form input with a preset selection of words?
For example it would allow a user to start a the word "Are" or "What" but not "Why".
You can use the following Regex. (This is really primitive and should be improved according to your case.)
^(Why|Are).*$
HTML5 input pattern example:
<form>
<input type="text" pattern="^(Why|Are).*$">
<input type="submit">
</form>
Test here.
You can add change or input event listener to it and validate the content. To avoid false negatives with initial few letters you can start checking after the input string contains a space. You don't need a library to do that. Plain old JS will do the job.
var input = document.getElementById("myinput");
input.addEventListener('input', validate);
function validate(e) {
var validStart = ['why', 'when'];
var tmpVal;
if (this.value.indexOf(' ') !== -1) {
tmpVal = this.value.toLowerCase().trim();
if (validStart.indexOf(tmpVal) === -1) {
input.classList.add('notvalid');
} else {
input.classList.remove('notvalid');
}
} else {
input.classList.remove('notvalid');
}
}
JSFiddle: http://jsfiddle.net/ofx2yhzm/1/
Very similar to Strah's answer, but here it is anyway:
function checkValue(el) {
// Trim only leading whitespace so responds when first space entered
// and break into words
var words = el.value.replace(/^\s+/,'').split(/\s+/);
// List of allowed words
var allowed = ['are','what'];
// Element to write message based on source element
var msg = document.getElementById(el.id + 'Msg');
// Clear error message by default
msg.innerHTML = '';
// Only do something if at least one word has been entered
// Could also check if first word has more letters than
// longest allowed word
if (words.length > 1) {
// Check if first word is allowed
if ( allowed.indexOf(words[0].toLowerCase()) == -1) {
msg.innerHTML = 'Input must start with one of ' + allowed.join(', ');
}
}
}
Some markup:
<input id="foo" oninput="checkValue(this);">
<span id="fooMsg"></span>
This allows the user to at least enter a word before being given an error. They should also be given some onscreen hints to let them know which words to use, rather than having to get it wrong first (which is bound to happen a lot).
Html:
<form name="myform" method="post" action="#" onsubmit="return validate()">
<input type="text" name="val" />
<input type="submit" value="Submit" />
</form>
Javascript:
window.validate = function(){
data = document.forms['myform']['val'].value;
var starts = ['hi','he'];
for (var i = 0; i <= starts.length; i++)
if (data.indexOf(starts[i]) === 0) return true;
return false;
}
And of course you could also use Regex tho I guess that's a little more inefficient.
Something like this?: http://jsfiddle.net/4jasrbob/