Issue with text area key down event using jQuery - javascript

We're having problems trying to implement a word counter similar to the one on twitter which decrements when the user types in the text field. Unfortunately it's quite glitchy as once you've deleted all the characters via backspace it displays that you only have 84 characters left (unless you hit backspace again). If you it the delete button the counter goes down even when it has removed nothing from the screen at the end of the text(I'm guessing it removes the 'invisible' character that is causing it to say 84 instead of 85 in the example before). All I want if for it to operate like the one on twitter
/* Limit textarea for cancelation policy to 85 characters*/
$('.counter').text(85-($('#txtCpolicy').val().length));
$('#txtCpolicy').keydown(function(e) {
var current = $(this).val().length;
$('.counter').text(85 - ($('#txtCpolicy').val().length));
if(current >= 85) {
if(e.which != 0 && e.which != 8) {
e.preventDefault();
}
}
});
Hope you can help

Change your code to keyup instead of keydown. Keydown triggers before the text is added to the textarea. Seems to work once you change it.

Related

How to clear a textarea value in jQuery?

I'm trying to validate keycode entry by adding an alert when a user types a key that isn't expected, and then clearing the text area. The alert functions correctly but the text area isn't clearing.
I've checked the documentation here, but I can't see an area with my .val() line. I've also tried this: $("#noteNumberInput").attr('value', "");
Scenario: I type 1-9 in the text box and get no alert (works fine), if I type a letter a-z for example, the alert pops up but the letter remains in the text box.
EDIT:
Something I've noticed is that it does clear the textarea after the first key. If I type the letter 'a' and then 'b', the 'a' is removed and replaced with a 'b'.
HTML:
<textarea id="noteNumberInput" placeholder="Note number"></textarea>
JS:
var noteNumberInput = document.getElementById("noteNumberInput");
//VALIDATE NOTE NUMBER TEXTAREA
function validate(key) {
var keycode = (key.which) ? key.which : key.keyCode;
//comparing pressed keycodes
if (keycode === 8 || (keycode >= 48 && keycode <= 57)) {
return true;
}
if (keycode < 48 || keycode > 57) {
alert("Please only enter the note number e.g. 1, 2..14 etc.");
$("#noteNumberInput").val("");
return false;
}
}
noteNumberInput.addEventListener("keydown", validate);
When you do $("#noteNumberInput").val('');, it removes all the content of the textarea, so if that's not what is happening, the problem is probably somewhere else.
Change noteNumberInput.addEventListener("keydown", validate); to use keyup
Using $("#noteNumberInput").val() will clear the textarea
EDIT
The problem is the keydown handler. In this case the function will be triggered followed by the display of alert & then the text area will be populated. But on using keyup the function will be triggered on release of the key.So by that time the textarea will be populated with value.
Change the keydown to keyup
var noteNumberInput = document.getElementById("noteNumberInput");
noteNumberInput.addEventListener("keyup", validate);
DEMO
Your only asking for the validate() function to actually execute when you've pressed the next key.
I think that´s not the best idea to trigger key events, because cut and paste and drag and drop can also change the input element.
try this:
Element.addEventListener('input', function(){
this.value=this.value.replace(/[^0-9,.]/g, '');
});
this must be adapted to textarea...

prevent "up arrow" key reseting cursor position within textbox

I recently added some predictive text input fields to the web-app I am supporting.
Big deal, right? Not really, seems like if your web-app doesn't do this -- you are already behind the times and your end-users are complaining. (At least that's how it is over here).
So, my question has to do with the "up" arrow key.
The predictive textbox has a onkeyup listener.
The handler segregates the key strokes and does something depending on the character the user entered.
The up arrow key allows the user to navigate in a div I created loaded with "suggestions."
I have several variables tracking indexes, etc...
Basically, when the user hits the up arrow I will change the id of the div to an id that has some css associated with it that will make the div appear as though it is selected. Additionally I will grab the value in that div and assign it to the textbox where the user is able to type.
The problem is an aesthetic one. Inherently with all text boxes I am learning, the up arrow key will reset the cursor position. This is happening just before I am writing the new value to the text field.
So, on each up arrow stroke, the user is seeing a jumping cursor in the textbox (it will jump to the beginning and immediately it will appear at the end).
Here's the code -
if (event.keyCode === 38 && currentUserInput.length > 0) {
// user has toggled out of the text input field, save their typing thus far
if (currentToggledIndex == -1) {
currentToggledIndex = autoFillKeywordsList.length-1;
savedKeywordUserInput = currentUserInput;
}
else {
// revert currently selected index back to its original id
document.getElementById("kw_selected").id = "kw_" + currentToggledIndex ;
// user has toggled back into user input field
if (currentToggledIndex == 0) {
currentToggledIndex = -1;
}
// user has toggled to the next suggestion
else {
currentToggledIndex--;
}
}
// 2. Determine next action based on the updated currentToggledIndex position
// revert the user input field back to what the user had typed prior to
// toggling out of the field
if (currentToggledIndex == -1) {
element.value = savedKeywordUserInput;
}
// mark the toggled index/keyword suggestion as "selected" and copy
// its value into the text field
else {
document.getElementById("kw_"+currentToggledIndex).id = "kw_selected";
element.value = autoFillKeywordsList[currentToggledIndex];
}
// 3. Determine what the user can do based on the current value currently
// selected/displayed
displayAppropriateButtonActions(element.value);
}
The funny thing is - the "down" arrow works perfectly since by default the down arrow key will place the cursor at the end of the string currently located in the textbox.
Ok, so things that I have already tried -
event.preventDefault();
event.stopPropogation();
I also tried to set the cursor position PRIOR to setting the new value to no avail using a setCursorPosition function I found on another post here. (Yeah, I was reaching with this one)
I tagged this as JavaScript and Jquery. I prefer to use JavaScript, but open to suggestions in Jquery too!
As Ryan suggested. how I achieved this in angular 4.x is
.html
<.. (keydown)="keyDownEvent($event)" >
.ts
keyDownEvent(event: any){
if (event.keyCode === 38 && event.key == "ArrowUp")
{
event.preventDefault();
//logic..
}
I think what you can do is when they move the cursor, grab that and find out what element it is ... then store it in a variable and focus() it and erase it and then put the value you stored back into it.
var holdme = $("#myelement").val();
$("#myelement").focus().val('').val(holdme);
This works for me when having weird cursor issues in jquery/javascript most of the time. Give it a try and if it doesn't work, let me know and I'll see what else might be wrong.
I found that it worked well to capture the caret position, blur, restore the caret position, then focus again.
myTextInput.onkeydown = function(e){
//some other code
if(e.key == "ArrowDown" || e.key == 40 || e.key == "ArrowUp" || e.key == 38){
var caretPos = this.selectionStart;
//do your stuff with up and down arrows
e.preventDefault();
this.blur();
this.selectionStart = caretPos;
this.selectionEnd = caretPos;
this.focus();
}
}
The caret will very briefly disappear, but I think you have to be incredibly observant to notice.

Javascript keyevent and JAWS screen reader

I have an application that does something (eg alert) each time a spacebar is pressed. This works fine if I am not using JAWS screen reader. However, once I load JAWS screen reader, it does not execute alert when I press the spacebar. I need to use JAWS so I need this to work. Here is the code snippet.
$(document).keypress(function(event) {
var chCode = ('charCode' in event) ? event.charCode : event.keyCode;
if (chCode == 32){ //32 is keyCode for spacebar
alert("spacebars!!!");
}
});
From my observation, it seems JAWS grabs the keyboard focus and wouldn't allow the spacebar event to fire. JAWS always reads "Space" when I press the spacebar but the alert event does not fire. How can I still get the alert or doSomething() to fire when the spacebar is pressed? How can I take control from JAWS or maybe share keyboard control with JAWS such that even though JAWS reads out the character I pressed (in this case Spacebar), it will allow my event (alert) to fire. Thanks.
More code:
$(document).keypress(function(event) {
var cc= ('charCode' in event) ? event.charCode : event.keyCode;
if (cc == 32)
{
spArray.push(Number(new Date()));
}
});
In general, it is not advisable to over-ride screen readers, even if they let you. There are quite a few JAWs keyboard commands (in conjunction with INS) that use the spacebar, and you'd probably lock those commands out.
If the area is primarily formed controls or interactive widgets then you could wrap it in an element with role="application". That puts a (windows) screen reader into 'forms' mode, where keys are passed through to the web-page.
Do not wrap everything in role="application", just the interactive area.
Update: With more information, this is about an audio-based capture where the user triggers an audio file, then triggers something again to set a time and pass the capture.
Using a native button, Jaws will pass through the use of enter (not sure about space, that isn't the usual 'activate' key). I'd suggest either checking for enter key (charcode 13 I think), or even onclick should work. On a native button/link it works across screen readers.
$(document).click(function() {
spArray.push(Number(new Date()));
});
Assuming that's in the right location so that it doesn't become active until needed. (JS isn't my strong point, but go with the enter key or onclick.
An event handler declared like this works in our application:
doKeyDown_: function (evt) {
var key = evt.keyCode || evt.which;
//arrows
if (key == 27 || (key >= 37 && key <= 40)) {
try {
if (key >= 37 && key <= 40) {
this.handleArrwos(evt);
} else {
this.handleEsc(evt);
}
...
Although it is based on the ZK platform, the inner engine is still JQuery. Please note that the event is keyDown (not keyPress) and how the pressed key is detected. The example is for Esc and arrow keys - Space should be no problem.
As for accessibility, our etire page is declared as role="application", since the entire content is a dynamically generated page, it's really an application. Only this way Jaws doesn't eat up about any possible keys combination.

Realtime Textarea Character Count in Titanium App (iOS)

I want to have a counter on my textfield that starts at 140 and subtracts the number of characters in the text area.
Here is my event listener:
contentArea.addEventListener('change', function(e) {
if(e.value.length >= 200) {
contentArea.value = e.value.substring(0, 200);
} else {
countLabel.text = 140 - e.value.length;
}
});
Basically, the user is allowed to submit if they have 140 or fewer characters. I don't want to just block it once they hit the limit, so I let them go a decent amount over. But I want to to update this count label with an accurate representation of their count.
The problem is checking the count on every change automatically accepts any autocorrect suggestion and causes for a really bad UX.
Is there any way around this?
Sounds like a messy way to do things but you could try adding a looping timer when the textArea focus() event fires, that keeps checking the length and updating the display. Then on the blur() event remove the timer.

Pass keydown event to another textbox

I'm trying to pass an keydown event from one textbox to another. What I mean with this is that if you, for example, press the 'a' key, some code should simulate that key as being pressed in the second textbox.
I do not want to just copy the value of the first textbox into the second - it should be on a per-key basis so to say. Suppose the first textbox contains abc and the second textbox is empty, when you then press the 'd' key in textbox 1, textbox 2 should only contain d.
What I already tried is (http://jsfiddle.net/E5qyr/1/):
$('#t1').keydown(function(e) {
$('#t2').keydown(e);
});
But this does not work (I guess I'm thinking too simple). I know I could append the character pressed by looking at e.keyCode, but also 'backspace' etc. has to be working.
Does anybody have an idea to pass a keydown event from one textbox to another?
Textarea elements don't have listeners automatically installed to them, so triggering a 'keydown' event for the #t2 will not show a response. What you want is to just add the text you get from the #t1 keydown event (of which you are listening) and append it to your #t2.
UPDATED with support for backspace. Other codes found here.
Example:
$('#t1').keydown(function(e) {
if (e.which == 8) { //Backspace
this.text(this.val().substr(0, this.val().length - 1));
} else {
$('#t2').append($('#t1').val());
this.empty();
}
});
Why not replace textbox value onkeydown? It seems it would be more simples to just do txt1.text = txt2.text instead of appending the existing strings in txt1.
Something like this?
$('#t1').keydown(function(e) {
var char = (e.keyCode == 8) ? '' : String.fromCharCode(e.keyCode + (e.shiftKey ? 0 : 32));
$('#t2').val(char);
});

Categories

Resources