Select different word each time TAB key is pressed - javascript

Move across each word in a sentences.
I have created shortcut key for enter in my application as, it will move towards and focus each input control in my page.
I need to set keyboard shortcuts for tab as, it has to select each string of a sentences which are in some textbox. For example txtAddress contain value like "Hi i am new user", if I press tab key it has to select a string "hi" then "i" then "am" then "new" then "user" after that it has to focus a next input control.
I have tried with following JS to focus next input control but don't know how to select each word in textbox.
$(document).unbind('keydown');
$(document).bind('keydown', 'tab', function assets() {
try {
var inputs = $(":input:not(input[type='hidden'])");
var CurInput = inputs.get(inputs.index(document.activeElement));
var nextInput = inputs.get(inputs.index(document.activeElement) + 1);
if (CurInput && nextInput.type == "text" && CurInput.style.display != "none") {
var strval = CurInput.value;
if (!strval) {
if (nextInput && nextInput.type != "hidden" && nextInput.style.display != "none") {
nextInput.focus();
}
}
}
else if (nextInput && nextInput.type != "hidden" && nextInput.style.display != "none") {
nextInput.focus();
}
return false;
}
catch (e) {
}
});

http://jsbin.com/cihahigevo/1/edit?html,js,output
var textarea = $('textarea')[0],
index = 0;
$(document).on('keydown.tab', function(e){
if( e.keyCode == 9 ){
textarea.focus();
textarea.value = textarea.value.trim() + ' ';
index = textarea.value.indexOf(' ', index) + 1;
textarea.setSelectionRange(0, index);
}
return false;
});

It's never a good idea to override a users keyboard, especially the tab button.
The tab button is used by people who (for whatever reason) don't use a mouse to navigate sites by 'tabbing' between buttons, form fields, etc.
If you remove this functionality by overriding the tab key, you've suddenly made your site unaccessible to these users.
You may also run afoul of you countries laws on website accessibility (the Disability & Discrimation act in the UK).

Related

How do I detect the "enter" key and "shift" key at the same time to insert a line break

I'm trying to create a note system. Whatever you type into the form gets put into a div. When the user hits Enter, they submit the note. However I want to make it so when they hit Shift + Enter it creates a line break a the point where they're typing (like skype). Here's my code:
$('#inputpnote').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode=='13' && event.shiftKey){
$("inputpnote").append("<br>");
}
else if(keycode == '13'){
var $pnote = document.getElementById("inputpnote").value;
if ($pnote.length > 0) {
$("#pnotes-list").append("<div class='pnote-list'><li>" + $pnote + "</li></div>");
$('#inputpnote').val('');
}
}
});
#inputpnote is the form where the user enters their note and #pnotes-list is the place where the notes are being appended to. Thank you in advance!
I think for this you'd have to set two global variables, 1 for shitftKeyPress and 1 for enterKeyPress and then you'd need a keydown and a keyup to set those values and then you check to see if they are both true, because your logic is saying, when a key is pressed, execute this code, if you press a key and then press another key, the only that will happen is the function will be called twice.
EDIT:
Example code of what it should look like:
var hasPressedShift = false;
var hasPressedEnter = false;
$('#inputpnote').keydown(function(event){
if(shiftkey) {
hasPressedShift = true;
}
if(enterKey) {
hasPressedEnter = true;
}
});
$('#inputpnote').keyup(function(event){
if(shiftkey) {
hasPressedShift = false;
}
if(enterKey) {
hasPressedEnter = false;
}
});
$('#inputpnote').keypress(function(event){
if(hasPressedShift && hasPressedEnter) {
// Do something
}
});
This was a quick mock up, but it's similar to how it should look

Replacing input text when tab is pressed ( Chrome Extension )

So basically what I'm trying to do is identify if the input bar has "y" typed in it and when tab key is pressed replace that y with "youtube ".
Javascript
var input = document.getElementById('searchbar').value;
var words = input.split(" ");
$("#searchbar").keydown(function(e) {
if(e.keyCode == 9) {
e.preventDefault();
if(input == 'y') {
$('#searchbar').text('youtube');
}
}
});
Currently I'm not getting any error messages, its just not working. The tab key also moves the focus away from the input bar.
Here is why
You should be getting value on keydown , not on page load as at the time of loading page value is empty.
As you are using jquery , get current value of input using jquery facade/selector
Finally you update the input box value not text
Try this
$("#searchbar").keydown(function(e) {
var input = $('#searchbar').val();
var words = input.split(" ");
if(e.keyCode == 9) {
if(input == 'y') {
$('#searchbar').val('youtube');
}
e.preventDefault();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter Search Term
<input type="text" id="searchbar">

Add hotkeys via JS excluding area inside textarea / input and skipping when Ctrl, Alt or Shift is pressed

I tried to use this for a simple hotkey function, that reacts to keypress for some keys, but doesn't if your editing in the box with the given ID. Unfortunately now Hotkeys are disabled always. I get the alert() all the time :(
the textfield is on e.g. http://tyrant.40in.net/kg/news.php?id=160#comments
Inside the text area it works but my script does not recognize, whether I'm inside the text area or outside (it also doesn't help to click in textarea and click outside).
Please help me.
I also tried to do it another way by selecting (!$('#tfta_1 #search')) instead of $('html'), so that the hotkeys do not work wenn you are in of of these IDs. Unfortunately this did not work ether.
edit: the js also has tocheck if crtl, alt, shift to avoid interpret
// Hotkeys (listen to keyboard input)
$('html').keypress(
function(event){
// is cursor at the beginning / end of edit box
var textInput = document.getElementById("tfta_1"), val = textInput.value;
var isAtStart = false, isAtEnd = false;
if (typeof textInput.selectionStart == "number") {
// Non-IE browsers
isAtStart = (textInput.selectionStart == 0);
isAtEnd = (textInput.selectionEnd == val.length);
} else if (document.selection && document.selection.createRange) {
// IE branch
textInput.focus();
var selRange = document.selection.createRange();
var inputRange = textInput.createTextRange();
var inputSelRange = inputRange.duplicate();
inputSelRange.moveToBookmark(selRange.getBookmark());
isAtStart = inputSelRange.compareEndPoints("StartToStart", inputRange) == 0;
isAtEnd = inputSelRange.compareEndPoints("EndToEnd", inputRange) == 0;
}
// combine information -> is cursor in edit box?
var eb = isAtStart + isAtEnd;
// if in comment box
if ( eb ) {
// do nothing
alert('You are in the comment box');
}
// if key 'p' is pressed
else if (event.which == 112){
// open profile page
window.location = home + 'profile.php';
}
// if key 'q' is pressed
else if (event.which == 113){
// open quests overview
window.location = home + 'quests.php';
}
// if key 'r' is pressed
else if (event.which == 114){
// open raids overview
window.location = home + 'raids.php';
}
// if key 'f' is pressed
else if (event.which == 102){
// open fraction tracker
window.location = home + 'factiontracker.php';
}
}
);
You need to check the event.target property.
if ('textarea' == event.target.tagName.toLowerCase()) {
return;
}
Or:
if ($(event.target).is('textarea')) {
return;
}
As for the modifier keys, see event.shiftKey, event.ctrlKey and event.altKey.

Get the id of element focus is moving to in jQuery.blur event?

I've written some code using jQuery to do an ajax call and display a message on the page when the user moves focus away from a field. My field is called txtLogin and the user types in some text and clicks a button to create a new user account in a database using the given txtLogin value.
The issue is that a valid value must contain four letters, a dash, and then four more letters. My client insists that the form should have two fields, one for the first four letters, and another for the second four letters.
Suppose that these two fields are called txtLogin0 and txtLogin1. I still want to do an ajax call when the user moves focus away from the field, but the ajax call should not be invoked when the user moves from one of the two fields to the other!
My current code looks like this.
$('#txtLogin').blur(function() {
var login = $(this).val();
var isValid = testLogin(login);
if (!isValid) alert('Login is invalid');
});
I imagine my new code looking like this:
$('#txtLogin0').add('#txtLogin1').blur(function() {
var focusId = The Id of the newly focused element
if (focusId==='txtLogin0' || focusId==='txtLogin1) return
var login = $(#txtLogin0').val() + '-' + $('#txtLogin1').val();
var isValid = testLogin(login);
if (!isValid) alert('Login is invalid');
});
How can I get the id of the element that the focus moves to in the jQuery.blur event?
A simple hack is to create two var to store the current and previous element in onfocus and onblur and call the validate method inside a timer which will be triggered in 0 milli seconds.. Try below code and I think it is close to what you want.
DEMO
var prevEl, curEl;
$(document).ready(function() {
$('#txtLogin0, #txtLogin1').blur(function() {
prevEl = this.id;
setTimeout(validateLogin, 0);
}).focus(function() {
curEl = this.id;
});
});
function validateLogin() {
if ((prevEl === 'txtLogin0' && curEl === 'txtLogin1') || (curEl === 'txtLogin0' && prevEl === 'txtLogin1')) {
return;
}
prevEl = ''; curEl = '';
var login = $('#txtLogin0').val() + '-' + $('#txtLogin1').val();
var isValid = testLogin(login);
if (!isValid) alert('Login is invalid');
}
function testLogin(txt) {
return false;
}
var focusId = $(this).attr('id');

Javascript: How to make this function working for click effects

I am designing a page where it displays the staff details in following structure :
user can click anywhere in the details box and the checkbox will get selected along with the change in the className of the details <div> box.
The problem i m facing is when i click anywhere in the details box it works fine.. but when i click on checkbox it only changes the className but doesnt make any changes to checkbox.
Also there is one condition, few users are allowed to selected limited staff at a time and few are allowed to select all of them..
I have assigned a myClick() function to the outer <div> box (one with red border)
and the function is :
var selectedCount = 0;
myClick = function(myObj,event)
{
var trgt =(event.srcElement) ? event.srcElement : event.target;
tgName = trgt.tagName;
//following statement gives me correct details element event though i clicked on any child tags
theElem = (tgName == 'DIV') ? trgt : ( (tgName == 'B') ? trgt.parentNode.parentNode : trgt.parentNode);
if(allowed_selection == 'unlimited')
{
if(theElem.className == 'details_clicked')
{
theElem.className = 'details';
theElem.getElementsByTagName('input')[0].checked = false;
}
else if(theElem.className == 'details_hover')
{
theElem.className = 'details_clicked';
if(tgName != 'INPUT') theElem.getElementsByTagName('input')[0].checked = true;
}
}
else
{
if(theElem.className == 'details_clicked')
{
theElem.className = 'details';
theElem.getElementsByTagName('input')[0].checked = false;
selectedCount--;
}
else if(theElem.className == 'details_hover')
{
if(selectedCount == allowed_selection ) return false;
theElem.className = 'details_clicked';
//i think, this is the suspicious area for errors
theElem.getElementsByTagName('input')[0].checked = true;
selectedCount++;
}
}
return false;
};
The problem is these return lines in your function:
return false;
When you connect an event to a form element that performs an action, such as a checkbox or button, returning false will prevent that default action. It stops the event from taking place as it regularly would.
You could try something like this at the top of your function:
var returnValue = (tgName == 'INPUT' && trgt.type == "checkbox") ? true : false;
And then when calling 'return ', use:
return returnValue;
If you return true you allow the checkbox to act as normal and check / uncheck itself.

Categories