Restrict character/string/word in input - javascript

My function, addthisTxt, is not checking the length. It should not exceed 11. Below is what I have tried so far; I'd like to keep on adding text until it reaches the max length, otherwise it should restrict the user from adding more.
HTML
<input type="checkbox" name="chkbxr" value="add this offer on wrapper"
(change)="addthisTxt($event.target.getAttribute('txt'), $event.target.checked)">
JavaScript
addthisTxt(txt, checked): void {
if (checked) {
if((this.v.offerName.length +txt.length) >= 55){
this.v.offerName = this.v.offerName + txt;
}
this.v.offerName = this.v.offerName;
}
}

You are setting the value on this.v.offerName. The UI element is not bound to this JavaScript variable and you need to set the value of the UI input element to restrict the value.

Related

Html input field set maximum value [duplicate]

This question already has answers here:
How to prevent inserting value that is greater than to max in number field in html
(2 answers)
Closed 5 years ago.
the max property does not work if i put a number in the field. Why?
it works only when i change the value with the arrows.
JS Fiddle
HTML
<input id= "0" class='labelmax form-control'
type='number' name='max_label' min='0' max='99' value='1'>
With HTML5 max and min, you can only restrict the values to enter numerals. But you need to use JavaScript or jQuery to do this kind of change. One idea I have is using data- attributes and save the old value:
$(function () {
$("input").keydown(function () {
// Save old value.
$(this).data("old", $(this).val());
});
$("input").keyup(function () {
// Check correct, else revert back to old value.
if (parseInt($(this).val()) <= 99 && parseInt($(this).val()) >= 0)
;
else
$(this).val($(this).data("old"));
});
});
For it work automatically you have to wrap your input within a form and add a submit button to that form
If you don't want to wrap it in a form and want maximum customisation you'll have to use Javascript and setup an event handler that will listen for user input and act accordingly
You can use something like below by making use of simple JavaScript. In your code I dont see any JS.
document.getElementsByClassName('labelmax form-control')[0].oninput = function () {
var max = parseInt(this.max);
if (parseInt(this.value) > max) {
this.value = max;
}
}
<input id= "0" class='labelmax form-control' type='number' name='max_label' max='99' value='1'/>

HTML5 : Input field with the type of 'number' will still accept higher value than its 'max' using keyboard inputs

Hello guys need some help here. i want to have limit the numbers inputted in my input field by putting max attribute to it. i have no problem with that until i use my keyboard to input data on it. seems like the max attribute is not filtering the input coming from the keyboard.
e.g
<input type="number" max="5" />
i can't go until 6 using the up and down arrow but when i manually put 6 using keyboard it's accepts it. how can i prevent? thank you
You would need to use JavaScript to do it. This will not let the user enter a number higher than 5:
<input type="number" max="5" onkeyup="if(this.value > 5) this.value = null;">
Another possible solution is to completely block the keyboard input by replacing onkeyup=".." event in the code above with onkeydown="return false".
have no problem with that until i use my keyboard to input data on it.
seems like the max attribute is not filtering the input coming from
the keyboard
This is how HTML5 validation/constraint work. However, it will invalidate when the form submits. Alternatively, you can validate it yourself. To validate yourself, you need to wire up Javascript and call the checkValidity() on the input element.
checkValidity() of the constraints API will check the validity state of the element and will return the state of whether the input element validate or not. This will also set the validity object on the input so that you can query more details.
Ref: https://html.spec.whatwg.org/multipage/forms.html#constraints and https://html.spec.whatwg.org/multipage/forms.html#form-submission-algorithm
You can also use the :invalid selector in CSS to highlight invalid inputs.
Example Snippet:
var input = document.getElementById('test'),
result = document.getElementById('result');
input.addEventListener('blur', validate);
function validate(e) {
var isValid = e.target.checkValidity();
result.textContent = 'isValid = ' + isValid;
if (! isValid) {
console.log(e.target.validity);
}
}
input[type=number]:invalid {
border: 2px solid red;
outline: none;
}
<label>Enter value and press tab: </label><br/>
<input id="test" type="number" min="1" max="10" />
<hr/>
<p id="result"></p>
You can use javascript to restrict the maximum input value to 5.
HTML
using oninput as a event handler
<input type="number" max="5" oninput="checkLength(this)" />
JS
function checkLength(elem) {
// checking if iput value is more than 5
if (elem.value > 5) {
alert('Max value is 5')
elem.value = ''; // emptying the input box
}
}
DEMO
An Utility Function to Solve Two Problem
Problem 1: Limit user input to maximum n digit
For this use n number of 9 as max parameter. As an example if you want to limit user input in 4 digit then max param value will be 9999.
Problem 2: Limit user input at a maximum value
This is intuitive. As an example If you want restrict the user input to maximum 100 then max param value will be 100.
function getMaxInteger(value, max) {
if(!value) return;
if( parseInt(value) <= max ) {
return value;
}
return getMaxInteger(value?.substr(0, value?.length-1), max);
}
function maxInt(value, max) {
return getMaxInteger(value?.replace(/\D/,''), max);
}
Use this maxInt method on input change handler
ngModelChange for Angular
onChange for React
v-on:change or watch for Vue
onkeyup="if(this.value > <?=$remaining?>) this.value = null; else if(this.value < 1) this.value = null;"

Keeping Submit Button Disabled Until Form Fields Are Full

Would someone be able to take a look at my code and see what I'm missing here?
I have a multi-page form with quite a lot of inputs, and I would like to keep "next page" buttons and the final "submit" buttons disabled until all the fields are full.
I am trying to recreate the process on a smaller scale but in my tests, I cannot seem to re-enable the disabled submit input. I've checked the console and the JS is logging the variable elements so I'm not sure what I'm missing.
function checkForm()
{
var elements = document.forms[0].elements;
var cansubmit= true;
for(var i = 0; i < elements.length; i++)
{
if(elements[i].value.length == 0 || elements[i].value.length == "" || elements[i].value.length == null)
{
cansubmit = false;
}
document.getElementById("myButton").disabled = !cansubmit;
}
};
<form>
<label for="firstName">First Name:</label> <input type="text" id="firstName" onkeyup="checkForm()" />
<br />
<label for="lastName">Last Name:</label> <input type="text" id="lastName" onkeyup="checkForm()" />
<button type="button" id="myButton" disabled="disabled">Test me</button>
</form>
Your elements array includes your button, which has no value. This will cause your loop to always evaluate to cansubmit = false;.
Try this instead: https://jsfiddle.net/e00sorLu/2/
function checkForm()
{
var elements = document.forms[0].elements;
var cansubmit= true;
for(var i = 0; i < elements.length; i++)
{
if(elements[i].value.length == 0 && elements[i].type != "button")
{
cansubmit = false;
}
}
document.getElementById("myButton").disabled = !cansubmit;
};
Answer was already accepted, but here are a few other things you might consider:
The way you have it set up now, for absolutely anything other than an empty string "" you're setting button.disabled = false and enabling the button.
You're checking value.length 3 times, but you actually want to
check .value instead. The length property is only a numeric
value for how many code units are in the string - it won't ever be
"" or null, so the only thing you're really checking is the very
first condition for an empty string of length 0.
You're also not accounting for multiple white spaces in a blank string, so " " would be valid) ... or
special characters, so this would be valid: (function goodByeWorld(evil){//do the bad things})();
You're running the checkForm() function on all form elements
(including the <button>) after every single keystroke. This is unnecessary.
Aside from including <button>, which was pointed out in the accepted answer & will always cause this to fail, you should either validate each individual form element with inline error checking
(preferable), or validate all of them once just prior to submission (preferable to server-side validation & kicking it back after submission).
You could bind to onblur() instead and send the current element's value as an argument once that field loses focus. e.g. change to: function checkValue(value) {//validate the value}) and either onblur = checkValue(this) in the HTML or preferably a non-inline event handler that lives in the JS file instead.
You could still do it onkeyup = checkValue(this) to check after every keystroke, but change the function to only check 1 element instead of checking t.h.e. e.n.t.i.r.e. f.o.r.m. dozens of times.
This approach would let you individually keep track of each separate form element's validity (lots of options here depending on what "valid" means - store an array of values, objects with values or "valid/invalid" flags, etc, switch on the field labels to validate this for different types of information). You can run additional validation on the individual elements as well (e.g. min/max name length, eliminating special characters, etc), and display real-time error checking messages next to each form element.
You're defaulting to cansubmit = true which doesn't make much sense, given what you intend for this code to do. Using !cansubmit only serves to confuse yourself & others reading the code. For readability, consider inverting it to disableSubmit so it's in sync with the button.disabled state, which should only be true or false.
Or you can use jQuery.
<script type="text/javascript">
function checkForm() {
var cansubmit = false;
$('form input[type="text"]').each(function (index, element) {
if (element.value == "") {
cansubmit = true;
}
});
document.getElementById("myButton").disabled = cansubmit;
}
</script>

Increment input value using mouse wheel

I'm trying to increase/decrease the value of input field using mouse wheel. I've put together the following code. It's working fine, but there's a small problem.
The behaviour I want is to be able to increment/decrement the input value using mouse wheel once I focus on the element. Mouse doesn't have to be hovering the element. The following code performs this. But if I use wheel while hovering the input element, the value is incremented/decremented by 2 instead of 1.
var hoveredInput = null;
$('input[type="number"]').on("focus", function(e) {
hoveredInput = this;
});
$('input[type="number"]').on("blur", function(e) {
hoveredInput = null;
});
$(window).on("wheel", function(e) {
if (hoveredInput) {
if (e.originalEvent.deltaY < 0) {
var currentValue = parseInt(hoveredInput.value, 10);
var newValue = currentValue + 1;
if (newValue > parseInt(hoveredInput.max, 10)) {
newValue = hoveredInput.max;
}
hoveredInput.value = newValue;
} else {
var currentValue = parseInt(hoveredInput.value, 10);
var newValue = currentValue - 1;
if (newValue < parseInt(hoveredInput.min, 10)) {
newValue = hoveredInput.min;
}
hoveredInput.value = newValue;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" value="0" min="0" max="255" />
After some experimenting, I figured that there's a similar behaviour for up and down arrow keys. Up and down arrow keys, on a number input, increments/decrements the value. And I suppose, this behaviour conflicts with my code. Causes it to increment by 2, even though the code doesn't execute twice.
I've just realized that this might be a Chrome specific problem. Chrome let's you increment/decrement number input value using mouse wheel if you focus and hover the element. However, it works in a really weird way.
If I just add <input type="number" /> in a blank HTML page, this mouse wheel increment doesn't work. To make it work, I simply add window.onwheel = function() {};. This doesn't make any sense. Also this seems to work on JSFiddle and JSBin without onwheel assignment on the window.
Going back to the actual problem, can I disable the default mouse wheel increment on the element, so that I can use my custom one? Or is there another approach that I can use?
I'm not sure why you would be considering not using preventDefault() to prevent the default action. You are changing what the UI action will be under these circumstances. You should, of course, use preventDefault() to prevent the default action. If you don't use preventDefault() then there would be some unexpected consequences to using the scroll wheel when the <input type="number"> is focused. Without preventDefault(), what combination of unexpected consequences would occur under those conditions will depend on the browser that is being used to view the page.
I am unable to duplicate a conflict with using the cursor keys to change the input value. Obviously, if all you are using to limit the minimum and maximum values of the <input> is the code for the mouse wheel, then those limits will not function for any other method of entry. You could use the min and max attributes for limiting values. Doing so would be better for multiple reasons, including that it affects all methods of entering a value and as it allows defining those ranges per <input> instead of one set of limits for all <input type="number">. I have changed the code so that your code also uses these attributes.
If you do this, you may want to consider adding a CSS style to indicate that the <input type="number"> element has focus. Doing so will make it more clear to the user why the mouse wheel is not doing what they normally expect from their browser's UI.
I suggest you try this with multiple browsers to see if it is something you desire. Personally, at least in the testing I have done on this page, I like the behavior.
NOTE:
Your use of the focus and blur events is overly complex. I have changed the code to directly find the focused element using document.activeElement.
//Exclude one specific element for comparing this UI vs. the browser's default.
var excludedEl = document.getElementById('exclude');
$(window).on("wheel", function(e) {
focusedEl = document.activeElement;
if(focusedEl === excludedEl){
//Exclude one specific element for UI comparison
return;
}
if (focusedEl.nodeName='input' && focusedEl.type && focusedEl.type.match(/number/i)){
e.preventDefault();
var max=null;
var min=null;
if(focusedEl.hasAttribute('max')){
max = focusedEl.getAttribute('max');
}
if(focusedEl.hasAttribute('min')){
min = focusedEl.getAttribute('min');
}
var value = parseInt(focusedEl.value, 10);
if (e.originalEvent.deltaY < 0) {
value++;
if (max !== null && value > max) {
value = max;
}
} else {
value--;
if (min !== null && value < min) {
value = min;
}
}
focusedEl.value = value;
}
});
input[type="number"]:focus {
box-shadow: 0px 0px 1.5px 1px cyan;
}
/*For comparing UIs: May conflict with browser default, or user's theme.*/
#exclude:focus {
box-shadow: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
NOTE: Events are only caught while the mouse stays within the test portion of the stackoverflow page:<br/><br/><br/>
Uses changed UI (if focused, mouse wheel will increment/decrement):<br/>
<input type="number" value="0" id="firstNumberInput" min="0" max="255"/>
<br/>Uses browser default UI:
<input id="exclude" type="number" value="0" min="0" max="255" style="display:block"/>

How can I get the value from a series of textbox with same id

I have a series of textboxes with the same name
<%for(i=0;i<=nooftasks;i++){%>
<input type="text" id="duration"
name="duration" class="td4" onkeyup="durationFormat()">
}%>
In Javascript I have to add a colon after two digits
function durationFormat()
{
var duration = document.getElementsByName("duration").value;
if(duration.length==2){
duration=duration+":";
}
}
But I could not get the desired result as I could not get the string from the textbox of that particular text box.
Any ideas?
<input type="text" id="duration" name="duration" class="td4" onkeyup="durationFormat(this)">
<script>
function durationFormat(obj) {
if ((obj.value.length)== 2) {
obj.value+=":";
}
}
</script>
getElementsByName returns a NodeList not an Element. A NodeList is like an Array. You need to loop over it and apply your changes to each value in turn.
Even if you have used getElementById(which returns an Element) and had unique IDs for your inputs (you don't, this is invalid, fix it) then it still wouldn't modify the value. Copying the value property into a variable and then modifying it won't change the value property of the input. You would need to go back and then input.value = duration after you made your modification.
If you want to get the specific input that invoked the function, then:
stop using intrinsic event attributes. They are a pain
use addEventListener instead
use event delegation to simplify the attaching of the handler
examine the target property to determine which input was invoked
such:
<fieldset id="durations">
<legend>Durations</legend>
<%for(i=0;i<=nooftasks;i++){%>
<input type="text" name="duration" class="td4">
}%>
</fieldset>
<script>
function durationFormat(ev) {
var input = ev.target;
if (input.value.length === 2) {
input.value += ":";
}
}
document.getElementById('durations').addEventListener('keyup', durationFormat);
</script>
You have to loop into your elements with name duration.
function durationFormat() {
var duration = document.getElementsByName("duration");
for (var i = 0; i < duration.length; i++) {
if(duration[i].value == 2){
duration[i].value += ":";
}
}
}
The logic for this is:
Firstly, get all elements that have an attribute name with duration value in that property.
Secondly, you have to loop inside the array of elements you got when called .getElementsByName method.
To finish, you have to set the value of each element with a : at the end of the value if his value is 2.
For those that don't understand what duration[i].value += ":"; does, automatically gets the value of the input element at i position of the array and adds the value : at the end. It's exactly the same that if you do duration[i].value = duration[i].value + ":";. I prefer to use +=, because it's sorter. I never tested, but I think that it's also the fastest way for browsers to add some content at the end. It can also be used for string variables.

Categories