Move up by UP key from textarea jquery - javascript

In html form we need to move up or down using arrow keys to shift focus in the fields. following code works fine for all input elements. but in case of textarea there could be multiple lines so, if we move up or down cursor moves up or down in the textarea itself.
Now, I'm not getting how to move up the focus, if the cursor reaches in the first line of the textarea while pressing up arrow OR move down the focus if the cursor reaches at the end or in the last line of the textarea while pressing down arrow key.
Here is my partial code:
var INPUT_SELECTOR = ':input:enabled:visible';
var inputs = $(INPUT_SELECTOR)
$("form").on("keypress", "input", function(event){
// i is current input
if(event.keyCode === 38){ //action == 'up'
inp = inputs[i > 0 ? parseInt(i) - 1 : inputs.length - 1];
}
if(event.keyCode === 40){ //action == 'down'
inp = inputs[i < inputs.length - 1 ? parseInt(i) + 1 : 0];
}
// focus on the input
moveFocusTo(inp);
});
Our requirement for the up and down arrow keys is same as tab and shift+tab behaviour. everything is done, we have just stuck at textarea.

Sounds like you need to use
https://developer.mozilla.org/en-US/docs/Web/API/event.relatedTarget#1003983
event.relatedTarget
Then you can check to see during the event what element the user is focused on and act accordingly.

Related

Textarea and tab keys: Get \t instead of jumping to the next element

I am using a html textarea called userInput but whenever I press tab it just moves to the next element. How would I make the tab key create a tab, or at least some spaces, and not move to the next element?
Add an event listener for the keydown event, and prevent the event if it is a tab that've been pressed:
var ta = document.getElementById("ta");
ta.addEventListener("keydown", function(e) { // when a keydown happens
if(e.keyCode === 9) { // if the key that is pressed is a tab (keyCode 9)
var start = this.selectionStart, // get the selection start (or the cursor position if nothing is selected)
end = this.selectionEnd, // get the selection end (or the cursor position if nothing is selected)
value = this.value;
this.value = value.substr(0, start) + "\t" + value.substr(end); // add a tab in-between instead of the selected text (or at cursor position if nothing is selected)
this.selectionStart = this.selectionEnd = start + 1; // set the cursor to one character after the last start index (right after the newly added tab character)
e.preventDefault(); // IMPORTANT: prevent the default behavior of this event (jumps to the next element and give it focus)
}
})
#ta {
width: 100%;
height: 170px;
}
<textarea id="ta"></textarea>

Autoresize textarea remove rows on backspace

I have the following code for autoresizing a textarea:
HTML:
<textarea class="autoresize" id="txt" rows="2"></textarea>
JS:
$('#txt').keydown(function(e) {
var $this = $(this),
rows = parseInt($this.attr('rows'));
// on enter, add a row
if (e.which === 13)
$this.attr('rows', rows + 1);
// on backspace, remove a row -- THIS IS THE PROBLEM
if (e.which === 8 && rows !== 2)
$this.attr('rows', rows - 1);
});
It works well, but when I hit backspace to erase a letter from a word, it also removes rows, and that's my problem.
I want it to shrink back when the user "deletes" empty rows but I don't know how to achieve it.
If you want, you can check it out in this fiddle.
You need to check if the last line is empty. Demo.
if (e.which === 8 && rows !== 2) {
lines = $(this).val().split('\n');
if(!lines[lines.length - 1]) {
$this.attr('rows', rows - 1);
}
}
Just count the length of the text you've entered (in every keydown) and then when you use backspace check if the last character (get it using the index from the length) is \n, only then delete row.

Changing cursor position using arrow cursor keycode in javascript

My editor area:
<div id="myeditor" contenteditable="true"><div>
I could send and display keycodes using
$("#myeditor").text($("#myeditor").text() + String.fromCharCode(65))
which it displays "A" in my div of id 'myeditor'. But I am stuck sending Arrow Cursor Keycode to it. (left : 37; up : 38; right: 39; down : 40)
$("#myeditor").text($("#myeditor").text() + String.fromCharCode(39))
Ahh it doesnt work.. it is showing other ascii character (like ampersand or quote sign) which arent intended. Can you tell me a right way to do it?
I guess the reason is, all other characters are from keys that have some character associated with it. But arrow keys do not have ←,→ such characters associated with them. They just have some functions. Have you ever used arrow keys to input an arrow in a text box?
If you really want to use them to input arrows, you can do the following in your jQuery..
var element = $('#myeditor'),
elementText = element.text();
store = {
37: "←",
38: "↑",
39: "→",
40: "↓"
};
element.keydown(function( event ) {
var selection = window.getSelection().getRangeAt(0);
//getSelection gets the selected range of text, when nothing is selected,selection is empty.getRangeAt(0)makes selection from the start of selection.
var keyCode = event.which;
if( store[ keyCode ]) {
var n = document.createElement('span');
//Adds a new html element.
n.innerHTML = store[keyCode];
//Adds the arrow to the newly created html element.
selection.insertNode( n );
//insert the newly created html element.
}
});
Demo Fiddle by Connor →
or http://jsfiddle.net/ybPzP/10/
I used String.fromCharCode(0x2190) to compare left arrow character in javascript. If you alert this then you can see left arrow character is alerted.

Autotab input with javascript

I have 3 inputs that need to tab to the next when the max length are reached.
These 3 inputs come with values and when the user change the value of the first input it focus on the next and so on.
My problem is that since my second input has already the length it jumps to the third input. If the use input the values slowly it don't do this.
The source of the problem is that if the typing is too fast the first keyup event is fired after the second type and it fires on the second input.
I've written a jsfiddle with the problem and this is my function to wire the auto focus change.
function WireAutoTab(CurrentElement, NextElement) {
CurrentElement.keyup(function (e) {
//Retrieve which key was pressed.
var KeyID = (window.event) ? event.keyCode : e.keyCode;
var FieldLength = CurrentElement.attr('maxlength');
//If the user has filled the textbox to the given length and
//the user just pressed a number or letter, then move the
//cursor to the next element in the tab sequence.
if (CurrentElement.val().length >= FieldLength && ((KeyID >= 48 && KeyID <= 90) || (KeyID >= 96 && KeyID <= 105)))
NextElement.focus();
});
}
Is there any other event that I can use to prevent this? The behavior that I want is that even if the second input has value, it stops on it.

Change div value based on textbox value using jQuery

I created this fiddle that the div value changes based on your dropdown list selection. http://jsfiddle.net/qSkZW/20/
I want to take it one step further and this is to create a textbox field that if you add for example the number 2 it will change the div value to 240 (in real the 120 you find in the script it will be a php var). If it writes 3 then to 360.
Additionally there must be two limitations.
Prevent them from using non-numeric characters.
The maximum number is pre-configured (from a php variable). Like if the max value is set to 10, if the user writes 30 it will return to 10.
Thank you for your help.
Okay, so first, create a textfield (example id="textfield"), then modify your listener's action to
$("#quantity").change(function () {
var price = parseInt($(this).val(), 10)*120
$("#textfield").attr('value="'+price+'"');
# sets the default value of #textfield to the selection from #quantity
})
.change()
$("#textfield").blur(function () {
# when the element looses focus (they click/tab somewhere else)
var valid = /^\d{2}$/;
# this means any 2 numbers. change {2} to {3} or however many digits.
# you can also also use d[0-10] to identify a range of numbers.
if ( $(this).text() != valid ) {
$("#message").text("Only numbers please!");
$("#message").fadeIn();
# add <span id="message" style="display:none;"></span> next to #textfield
# enclose #textfield & #message in the same element (like <li> or <div>)
}
else {
$("#message").fadeOut();
}
});
Could you please provide more info about #2 (I don't have a clear understanding of what is supposed to happen)
Quick question: why are you trying to put a price in an editable element?
This will do it: http://jsfiddle.net/ebiewener/pBeM8/
You bind the keydown event to the input box in order to prevent the undesired characters from being entered, and bind the keyup event in order check the value & modify the div's height.
$('input').keydown(function(e){
if(!(e.which >= 48 && e.which <=58) && e.which !== 8 && e.which !== 46 && e.which !== 37 && e.which !== 39){ //prevent anything other than numeric characters, backspace, delete, and left & right arrows
return false;
}
})
.keyup(function(){
val = $(this).val();
if(val > 10){
val = 10;
$(this).val(10);
}
$('div').height(val * 10);
});
var max = 30;
$('input').keyup(function() {
var v = $(this).val();
v = isNaN(v)?'':v;
v = v > max ? max : v;
$(this).val(v);
$('div').html(v * 120);
});
http://jsfiddle.net/vWf2x/2/

Categories