jQuery - set max length for textarea - javascript

I want to have a textarea with a maximum length, and show the user how many characters are left (as it's done on twitter), but I can't seem to get it to be as good.
The requirements are:
Must show the current number of characters they've typed
Must remain accurate when a key is held down
Must remain accurate when backspace/delete is used
Must remain accurate when text in the box is selected and cut/delete by using the right click menu
Must allow the user to go over the limit (I hate it when a field actually prevents me from going over, it makes it harder to edit it down)
Is there a jQuery plugin to do this? Or is there a simple javascript way of doing it (the onChange method doesn't update as they're typing, and keydown/keyup would have troubles with mouse changes)
At the moment it seems like the best way is to have a function to do what I want (check the length and update the message), call it with keydown/keyup/change, and also poll it a few times per second. Is there a better way?

What you usually do is attach multiple event handlers pointing to a validating function, but you won't be able to stop the rightclick/paste with this...
$(document).ready(function() {
$("#myTextArea").live("change keydown keyup keypress", function() {
validate();
});
});
function validate() {
// validates #myTextArea
}

try this
$("#textarea").on('input',function(){
if(this.value.length > 50) {
alert("u cant input more.");
this.value = this.value.substring(0,50);
}
$('#counter').html(this.value.length + '/50');
});
maybe this code help u

Related

On focus input: insert value and move cursor to end

What I'm aiming for
When the user focuses the input: if it's empty, we insert the prefix text and move the cursor to the end. It should also work if they tab into the input.
Context/demo
I'm making a jQuery plugin that adds a flag dropdown next to an telephone number input. When the user focuses the input, it gets populated with a little prefix (the selected country's dial code). Demo here.
Problems
By default, the cursor will appear where ever they clicked i.e. potentially in the middle of the prefix). I found this mini plugin to move the cursor to the end, which works well if you put it in a click event handler, BUT then this wont fire if you tab into the input. I tried putting it in a focus event handler instead, but that didn't work (I think because the click event is fired after the focus event).
Bonus points
For a simple, elegant solution, using no global variables, and the least number of event listeners possible. Also if possible, don't show the cursor where they are clicking before moving it to the end.
This is the best solution I have come up with so far. It ticks all the boxes, except it's not the most elegant solution - I feel like I might be missing something obvious. Ideally, it would only require one event listener.
var input = $("input"),
prefix = "prefix ";
input.focus(function(e) {
if (!input.val()) {
input.val(prefix);
}
});
input.mousedown(function(e) {
// mousedown decides where the cursor goes, so if we're focusing
// we must prevent this from happening
if (!input.is(":focus") && !input.val()) {
e.preventDefault();
// but this also cancels the focus, so we must trigger that manually
input.focus();
putCursorAtEnd(input);
}
});
Here's a codepen demo.
Focus, clear value, then revert to original value
1st save the value to a temporary variable.
2ndly clear the input field
3rdly focus that empty field & again paste the saved value from temporary variable.
it will always focus to the end of the field.
$tempVal = $("#digibox_otp").val();
$("#digibox_otp").val('');
$("#digibox_otp").focus().val($tempVal);

Get the value of a textbox during cut event

I have trapped the cut event (jquery) on a textbox. What I want is to get the text on the textbox during the cut event is triggered.
I've tried accessing the data the user cut via evt.originalEvent.clipboardData.getData('text') but returns undefined.
My goal is to know if the user cut all the text (textbox is now empty) or not.
Thanks in advance
You can setTimeout with a duration of 0, which schedules a function for immediate execution. The nice thing is that the function will execute once the text has already been cut, so you can check then if your textarea is empty (which would mean that the user has cut all the text):
var ta = $('#YOUR_TEXTAREA');
ta.bind('cut', function() {
setTimeout(function(){
if (!ta.val()) {
// user cut the whole text.
}
},0);
});
You might also want to add a check before the setTimeout to test whether there is any text in the textarea before the text gets cut (if the user presses Ctrl^X without any text being selected, the cut event still triggers)
Hope I got you right:
In jQuery you could use something like this to see if a textbox is empty on every user's keyup:
var txt;
$('#textbox_ID').live('keyup', function() {
txt = $(this).val().length;
if(txt < 1) {
alert("textbox is empty");
}
});
This should work, because everytime the user releases a key and has the textbox focused, it checks if it's empty.
I would suggest looking at this, JavaScript get clipboard data on paste event (Cross browser), it is for the paste event but I'm sure you could do something similar and compare the current value to that on the clipboard, if they are exactly the same than the input would be empty, otherwise not.

really simple javascript to remove value in text box

iv got a really simple javascript question. Ill be using query for parts of it here but there are akin ways of doing it via javascript. basically, I'm writing a little script that makes it so when you click a text box with a value in it, it will take out the value so your can type (ex for most username boxes they have a little note in there). there are probably much better ways of doing this (i can already think of some) so feel free to suggest them as well. anyways I got that part running easily, the problem is that whenever a user clicks again all the data is removed, so if they just want to adjust something they can't. to solve this (ill show code in sec) i put a check variable and an if. this is what it looks like. (it doesn't work, btw)
var unumber = 0;
var pnumber = 0;
if(unumber<1){
$('#username').click(function(){
unumber = 1;
$('#username').val('');
});
};
if(pnumber<1){
$('#password').click(function(){
$('#password').val('');
pnumber = 1;
});
};
what I'm assuming happens is that every time some one clicks the variables are reset, and this leads to a more general question if this is this case, why would the whole script, not just the event handler, run? Im new to javascript so forgive me if this is a stupid question. Anyways, this is a really simple script and there are better and more efficient ways to do it, but how can it be done this way?
Your check for number less than 1, should be within the click handler
var unumber = 0;
var pnumber = 0;
$('#username').click(function(){
if(unumber<1){
unumber = 1;
$('#username').val('');
}
});
$('#password').click(function(){
if(pnumber<1){
pnumber = 1;
$('#password').val('');
}
});
Note that this is not very robust, it doesn't handle tabbing into the fields. To fix that, handle the focus event.
Another problem is that you don't get the message back if you don't type anything and leave the field. A better approach is to compare against the initial value when the field receives focus. If there's nothing in there when you leave the field, restore to the original value.
Here's a jQuery plugin for creating these placeholders: https://github.com/mathiasbynens/Placeholder-jQuery-Plugin
Also, newer browsers support a placeholder attribute that does exactly that http://www.paciellogroup.com/blog/2011/02/html5-accessibility-chops-the-placeholder-attribute/
I'd say the best way of doing this is to have a clear button inside the text input. See here for an example : How do I put a clear button inside my HTML text input box like the iPhone does?
No need for the messy number checking, use data on the element in question
This should work for you.
$('#username,#password').focus(function(){
if(!$(this).data('seen')) {
$(this).data('seen',true);
$(this).val('');
}
});
http://jsfiddle.net/DeZ7D/
You could store the placeholder and replace back on blur if the user hasn't entered anything.
more detailed implementation here:
http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html

Trigger onBlur on multiple elements as a single unit

I have two inputs that together form a single semantic unit (think an hours and minutes input together forming a time input). If both inputs lose focus I want to call some Javascript function, but if the user merely jumps between those two, I don't want to trigger anything.
I've tried wrapping these two inputs in a div and adding an onBlur to the div, but it never triggers.
Next I tried adding onBlurs to both inputs and having them check the other's :focus attribute through jQuery, but it seems that when the onBlur triggers the next element hasn't received focus yet.
Any suggestions on how to achieve this?
EDIT: Someone questioned the purpose of this. I'd like to update a few other fields based on the values contained by both these inputs, but ideally I don't want to update the other fields if the user is still in the process of updating the second input (for instance if the user tabs from first to second input).
I made a working example here:
https://jsfiddle.net/bs38V/5/
It uses this:
$('#t1, #t2').blur(function(){
setTimeout(function(){
if(!$('#t1, #t2').is(':focus')){
alert('all good');
}
},10);
});
var focus = 0;
$(inputs).focus(function() { focus++ });
$(inputs).blur(function() {
focus--;
setTimeout(function() {
if (!focus) {
// both lost focus
}
}, 50);
});
An alternative approach is to check the relatedTarget of the blur event. As stated in the MDN documentation this will be the element which is receiving the focus (if there is one). You can handle the blur event and check if the focus has now been put in your other input. I used a data- attribute to identify them, but you could equally well use the id or some other information if it fits your situation better.
My code is from an angular project I've worked on, but the principle should translate to vanilla JS/other frameworks.
<input id="t1" data-customProperty="true" (blur)="onBlur($event)">
<input id="t2" data-customProperty="true" (blur)="onBlur($event)">
onBlur(e: FocusEvent){
const semanticUnitStillHasFocus = (val.relatedTarget as any)?.dataset?.customProperty === "true";
// Do whatever you like with this knowledge
}
What is the purpose of this behavior ?
The blur event triggers when a field looses focus, and only one field can gain focus at a time.
What you could do, in case of validation for instance, is to apply the same function on blur for both the fields and check the values of the fields altogether.
Without a context, it is difficult to help you more.
d.

how to check if the value of a text input is empty right after the keypress event in javascript?

Here's the problem, in abstract terms: i have three input fields (A, B, C). two of them need to be text inputs (A and B), the third is of irrelevant type. I need to enable the third if A is not empty and B is not empty. I need to disable C if A is empty or B is empty.
The code
// empty is the empty function from the phpjs project
// framework used: jQuery
// A, B and C are classes here
$(".A, .B").keypress(function(){
if( !empty($(".A").val()) && !empty($(".B").val()) )
$(".C").attr("disabled","");
else
$(".C").removeAttr("disabled");
});
I want to be able to check this on keypress, but when requesting the value of the input that is edited when the keypress event occurs i get the value that was calculated before the keypress event.
Has anybody stumbled upon this before and solved it?
have you tried using the keyUp event?
Use the keyup event instead.
Attach your handler to the keyrelease event. The value should have been updated by then.
use a combination of handlers for keyup and change. the keyup handler will update as the user types (excepting edge cases like holding a key down, which doesn't seem like a concern here) and the change handler will catch things like the user cutting the text with mouse actions before they can switch to field C. as an added measure you could add verification on field C's focus event, to make sure A and B really have something.
$('.A, .B').keydown(function(event) {
if(!empty($('.A').val()) && !empty($('.B').val()))
$(".C").attr("disabled","");
else
$(".C").removeAttr("disabled");
});
At the keypress event, the value of the INPUT is not yet set. Hence you can't easily know if it is empty.
While the keyup fires, the value of the INPUT is set.
But things get worse. The user can empty the field with the mouse or the Edit menu of the browser. In that case keyup is not fired.
In our web app we auto-save the values. Like in Mac OS, if you know, there is almost no save buttons.
To allow a reaction here is more or less what we do:
onfocus: a setInterval starts polling every 120ms or so, and checks the input for any change
if there is a change do the relevant action
onblur: a clearInterval stop the polling

Categories

Resources