I want to limit number of chars in input text field.
Code I'm using:
function limitText(field, maxChar){
if ($(field).val().length > maxChar){
$(field).val($(field).val().substr(0, maxChar));
}
}
Event is onkeyup.
When I type some text in input field cursor stays on the end of text but focus is backed on start of the text so I can't see cursor.
What can be a problem.
Browser is FF, on IE and chrome it is working correctly
you can also do it like this:
<input type="text" name="usrname" maxlength="10" />
to achieve this with jQuery, you can do this:
function limitText(field, maxChar){
$(field).attr('maxlength',maxChar);
}
Your code is working in FF. Here is slightly modified version of your code:
$('input.testinput').on('keyup', function() {
limitText(this, 10)
});
function limitText(field, maxChar){
var ref = $(field),
val = ref.val();
if ( val.length >= maxChar ){
ref.val(function() {
console.log(val.substr(0, maxChar))
return val.substr(0, maxChar);
});
}
}
Demo
Related
I am currently working on limiting the allowed input in a numeric text field. I check the length of the value of the input field, if it is >= to the maxlength attribute, don't input anything.
$('input[maxlength]').on('keyup', '', null, function(event) {
var ref = $(this),
val = ref.val();
if ( val.length >= this.maxLength && event.which != 8){
return false;
}
}
However, if the currently value of the field ends in a decimal (eg "4."), then the val() method returns "4", which throws off the whole process. How can I read the contents of the input field while including the trailing decimal points?
http://jsfiddle.net/n3fmw1mw/329/ (Type in '4.' and you'll see what I'm talking about.)
EDIT: I've tried something from Mr. Hill's suggestion and now I have this
$('input[maxlength]').on('keydown', '', null, function(event) { //enforce maxlength on all inputs, not just text inputs
var ref = $(this);
ref.attr('type','text');
var val = ref.val();
if ( val.length >= this.maxLength && event.which != 8){
ref.attr('type','number');
return false;
}
ref.attr('type','number');
});
But now nothing is being inserted into my text box, even if debugging and seeing that we aren't returning false.
The decimal is being dropped because your input type is number. Set your input type to text.
<input type="text" id="textbox1"/>
Here's a working fiddle.
EDIT
Based on your new requirement of not being able to change the source, the code below should get you pointed in the right direction.
jQuery does not allow you to change the type of an element. To do it, you must remove the element and add one of the correct type in its place. The code below does just that.
Note: In an effort to make the code more reusable, I added a class to your element and then edited all elements with that particular class.
// Add class to identify that element type needs changed
$("#textbox1").addClass("numberToText");
// Swap number type input with text
$('.numberToText').each(function() {
$("<input type='text' />").attr({
id: this.id,
name: this.name,
value: this.value
}).insertBefore(this);
}).remove();
$("#textbox1").keyup(function() {
$('#log').append("Value: " + $('#textbox1').val() + '<br/>');
});
$(".button").click(function() {
$('#log').append("Value: " + $('#textbox1').val());
})
Here's a working fiddle.
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;"
I have a form with inputs which also has an iFrame embedded in the form which also has inputs (pseudo HTML):
<input type="text" name="one" value="one" />
<input type="text" name="two" value="two" />
<input type="text" name="three" value="three" />
<iframe
<input type="text" name="bacon" value="bacon">
</iframe>
<input type="text" name="four" value="four" />
<input type="text" name="five" value="five" />
When the user presses tab they are taken from input to input even inside the iframe fields selecting bacon after three. We all love bacon.
I also have some javascript that attempts to focus the next input on enter key:
$(document).ready(function() {
$(document).on('keydown', 'input', function(ev) {
// Move to next on enter
if (ev.which === 13) {
var inputs = $(':tabbable');
var next = inputs.index(this) + 1;
var input = inputs.eq(next == inputs.length ? 0 : next);
input.focus();
return false;
}
});
});
The problem is the javascript enter key code never focuses the bacon field, it will skip right over it. jsfiddle:
https://jsfiddle.net/54n8mqkh/4/
Let's all skip answers that include not using the iFrame. I know it is not an ideal implementation. However, I would accept ANY answer that allows the enter key to move through all the fields consistently including the iframe using any type of javascript. It does not have to be jquery specific.
I have tried a few different approaches to solve this but none I have found works. Thanks in advance to anyone who has a solution.
You need to focus inside of the iframe like so :
var frameBody = $("#IFrame_input").contents().find("input");
frameBody.focus();
I am going to answer my own question - after a few more hours I was able to solve my use case by expanding my selector to include the iframe. Then I build the array of inputs manually and while iterating I checked the node type for an iframe. If / when I encountered an iframe, I did the same select inside the iframe and added the inputs within the iframe:
$(document).ready(function() {
// Parent level helper function
window.tabToNext = function(me) {
var selector = ':tabbable, iframe';
var inputElems = [];
$(selector).each(function(index) {
var nodeName = $(this).prop('nodeName').toLowerCase();
if (nodeName == 'iframe') {
$(this).contents().find(selector).each(function(index) {
inputElems.push(this);
});
} else {
inputElems.push(this);
}
});
var inputs = $(inputElems);
var next = inputs.index(me) + 1;
if (next == inputs.length) next = 0;
var input = inputs.eq(next);
input.focus();
return false;
}
$(document).on('keydown', 'input', function(ev) {
// Move to next on enter
if (ev.which === 13) {
return window.tabToNext(this);
}
});
// Focus the first input
$('input[name=one]').focus();
});
FWIW: I could not just expand the selector as best I could tell and also I tried to use $.add to build the collection starting with an empty jQuery collection:
var foo = $([]);
foo.add(someElement);
... but it does not honor the order you add. It will re-order to the DOM according to the docs which SEEMS like it should be right, but for some reason my iframe child fields always ended up last and messed up the tab order.
Anyhow, I hope if someone else has this issue some day you find this helpful. Working solution:
https://jsfiddle.net/wbs1zajs/6/
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"/>
I am setting readonly="readonly" (in other words, true) via javascript:
document.getElementById("my_id").setAttribute("readonly", "readonly");
This is having the intended effect (making the field no longer editable, but its contents are submitted with the form) in FF, Safari and Chrome, but not for IE7. In IE7 I can still modify the contents of the text input field.
I have tried setting ("readonly", "true") as well, which works in all three other browsers that I am testing, but which IE7 also ignores.
Does anyone have experience with trying to do this with IE7? I do not want to use the disabled attribute as I want the value within the text input field to be submitted with the form.
Did you try this?
document.getElementById("my_id").readOnly = true;
try:
document.getElementById("my_Id").setAttribute("readOnly","readonly")
it is readOnly, O is capital!
<script type="text/javascript">
function blah(txt) {
var text = document.getElementById(txt).value;
if(text.length > 4 && document.getElementById('chk').checked == false) {
// ********* NOT WORKING WITH IE *************** //
//document.getElementById("ta").setAttribute('readOnly','readonly');
//document.getElementById("ta").readOnly="readOnly";
// ******** --- **********//
//document.getElementById("ta").disabled = true; // for disable textArea
document.getElementById("ta").blur(); // comment this when above line is uncommented or visa-versa
document.getElementById('chkBox').style.display = "block";
}
}
function unable() {
// document.getElementById("ta").disabled = false; // to unable textArea -- uncomment when disabling is used or visa-versa
document.getElementById('ta').focus();
document.getElementById('chkBox').style.display = "none";
}
</script>
<textarea id="ta" onkeydown="blah('ta')" ></textarea>
<div id="chkBox" style="display:none"><label> Please check this to continue....</label><input type="checkbox" id="chk" onclick="unable()"></div>
Or try:
document.getElementById("my_id").setAttribute("readOnly", true);
Please note as stated by #TheVillageIdiot, the O in readOnly is UPPER CASE. This should work from IE7 to IE11.