How to get Tab key click event on wrtting on text field? - javascript

can you please tell me how to get Tab key event in jquery ? Actually If user click Tab key while entering text in input field I want to show alert .
I am using this But not working ..
var myInput = document.getElementById("caseName");
if(myInput.addEventListener ) {
myInput.addEventListener('keydown',this.keyHandler,false);
} else if(myInput.attachEvent ) {
myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */
}
function keyHandler(e) {
alert("Hi")
var TABKEY = 9;
if(e.keyCode == TABKEY) {
this.value += " ";
alert("Tab")
if(e.preventDefault) {
e.preventDefault();
}
return false;
}
}

Just remove the this keyword in the following lines:
myInput.addEventListener('keydown',this.keyHandler,false);
and change it to :
myInput.addEventListener('keydown',keyHandler,false);
Check this fiddle out.

Related

Keypress in text input preventing typing

I have a text input that I want to execute a function when enter is pressed. I used if condition to determine if enter is pressed but this causes the user not to be able to type in the input box. What can I put in the else condition to allow them to type normally?
JsFiddle
function addItem(e) {
e.preventDefault(); // Prevent form being submitted
var text = $('input:text').val(); // Get value of text input
var itemArr = text.split(',');
var lngth = itemArr.length
for(i = 0; i < lngth; i++)
{
$list.append('<li>' + itemArr[i] + '</li>'); // Add item to end of the list
updateCount(); // Update the count
} // End loop
$('#addItems').val(''); // Empty the text input
return false;
}
$('#addItems').keypress(function(e) {
if(e.which == 13) {
addItem();
}
return false;
});
Remove return false; from the keypress function.
$('#addItems').keypress(function(e) {
if(e.which == 13) {
addItem();
}
else {
return true;
}
return false;
});
Jusr remove return false from the keypress event
You can see this Question
return false; successfully cancels an event across browsers if called at the end of an event handler attribute in the HTML.
and to prevent form from form being submitted, you can add onsubmit="return false" to the form
Demo

Select different word each time TAB key is pressed

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).

Adding keyboard shortcuts (up, down, enter) to search input suggestions div

I have a search suggestion div that appears when you keyUp an input. This works fine, but now I am trying to make keyboard shortcuts in action.
I want a behavior like when you click down keyboard arrow button a span gets selected and if it is selected then another span that is after gets selected, similarly, if you click up arrow an upward span gets selected, when you click enter then link opens.
I am stuck because I could not remove a:hover and could not add classes to it. Even after I have basically no idea how to do it. But I really tried hard and a lot..
Here is a jsfiddle link (type anything in field). maybe somebody will help me.
This code should go when the request is made and data is being returned:
<script type="text/javascript">
$(document).ready(function(){
total = 3;
$(".result-item").mouseenter(
function(){
hovered = $(this).attr("id");
total = 3;
$(".result-item").each(function(){
$(this).children("a").css({
'background-color':'#e4e4e4',
'color':'#000000'
});
$(this).find(".searchheading").css({
'color':'#191919'
});
$(this).find(".searchcaption").css({
'color':'#555555'
});
});
$(this).children("a").css({
'background-color':'#b7b7b7',
'color':'#ffffff'
});
$(this).find(".searchheading").css({
'color':'#ffffff'
});
$(this).find(".searchcaption").css({
'color':'#f1f1f1'
});
}
);
});
</script>
And this code on a page where request is made:
$("#suggestions").hide();
$("#search").bind('keyup', function(event){
if (event.which == 40 || event.which == 38 || event.which == 13) return false;
else
{
hovered = undefined;
lookup($(this).val());
}
});
$("#search").bind('keydown', 'down', function(evt){
if ($("#suggestions").is(":visible"))
{
if (typeof hovered == 'undefined')
{
$("#result-item-0").trigger("mouseenter");
return;
}
count = parseInt($("#"+hovered).attr("count"));
next = (count + 1);
if (next == total)
next = 0;
$("#result-item-"+next).trigger("mouseenter");
}
});
$("#search").bind('keydown', 'up', function(evt){
if ($("#suggestions").is(":visible"))
{
if (typeof hovered == 'undefined')
{
$("#result-item-"+(total-1)).trigger("mouseenter");
return;
}
count = parseInt($("#"+hovered).attr("count"));
prev = (count - 1);
if (prev == -1)
prev = (total-1);
$("#result-item-"+prev).trigger("mouseenter");
}
});
$("#search").bind('keydown', 'return', function(evt){
if ($("#suggestions").is(":visible"))
{
if (typeof hovered == 'undefined')
{
str = $("#search").val();
window.location.href = urlencode(str); // urlencode is a custom function
return false;
}
count = parseInt($("#"+hovered).attr("count"));
current = count;
$("#result-item-"+current).trigger("mouseenter");
$("#suggestions").fadeOut();
window.location.href = $("#"+hovered).children("a").attr("href");
}
});
})
;
Also I removed onkeyup="" attribute on element, this approach is nicer.

clearing radio input using jQuery

I have a bunch of radio buttons that are below. These radio buttons are part of a larger form and are optional, so If a user clicks on one, then decides he/she doesn't want the option selected, there is no way to undo this.
I was wondering if there was any jQuery etc, that, when clicking a link for example, clear any radio selection, based on the group name in the HTML?
Thanks
var group_name = "the_group_name";
// if jquery 1.6++
$(":radio[name='" + group_name + "']").prop('checked', false);
// prev than 1.6
// $(":radio[name='" + group_name + "']").attr('checked', false);
Working demo: http://jsfiddle.net/roberkules/66FYL/
var Custom = {
init: function() {
checkAllPrettyCheckboxes = function(caller, container){
// Find the label corresponding to each checkbox and click it
$(container).find('input[type=checkbox]:not(:checked)').each(function(){
if($.browser.msie){
$(this).attr('checked','checked');
}else{
$(this).trigger('click');
};
});
};
uncheckAllPrettyCheckboxes = function(caller, container){
// Find the label corresponding to each checkbox and unselect them
$(container).find('input[type=checkbox]:checked').each(function(){
$('label[for="'+$(this).attr('id')+'"]').trigger('click');
if($.browser.msie){
$(this).attr('checked','');
}else{
$(this).trigger('click');
};
});
};
I have created it in an init function, and adter then i called the init.
}
window.onload = Custom.init;
I have created a solution like roberkules' solution, except mine clears the radiobutton if you click the radiobutton itself while it's checked. Use this if you don't want to add an extra "Clear" button to your layout.
http://jsfiddle.net/P9zZQ/6/
// Requires JQuery 1.4+ (possibly earlier)
$(function () {
// Turn off a radiobutton if clicked again while on
var checkOff = function (event) {
var target = $(event.target);
if (target.is('label')) {
// deal with clicked label
if (target.attr('for')) {
// label has 'for' attribute
target = $('#' + target.attr('for'));
} else {
// label contains a radiobutton as a child
target = target.find('input[type=radio]');
}
}
if (target.is('input:checked[type=radio]')) {
event.preventDefault();
window.setTimeout(function () {
target.attr('checked', false);
}, 200);
}
}
// Find all radiobuttons and labels inside .radio-clearable containers
$(
'.radio-clearable input[type=radio], ' +
'.radio-clearable label').mousedown(function (event) {
// When clicked -- clear if it was checked
checkOff(event);
}).keydown(function (event) {
// When receiving space, escape, enter, del, or bksp -- clear if it was checked
if (event.which == 32 || event.which == 27 || event.which == 13 || which == 46 || which == 8) {
checkOff(event);
}
});
});
Usage: For any radiobutton you want to be clearable in this manner, wrap it in a container with class "radio-clearable".
The code is triggered by clicking or sending a key (Space, Escape, Enter, Del, BkSp) to the radiobutton element or to its label.

make use of the enter key

I have a list of urls(div) underneath an input field(div). I need the ability to come down in the list and than by hitting enter this will trigger some function designated to the url. This is the fidle: the script
Over the last days I have tried to much things to explain, but in conclusion none of it worked. Help would be appreciated.
After this line of code :
// set timers to do automatic hash checking and suggestions checking
setInterval(checkHash,500);
setInterval(checkSuggest,500);
Insert this :
$('#searchbox').keyup(
function (e){
var curr = $('#suggest').find('.current');
if (e.keyCode == 40)
{
if(curr.length)
{
$(curr).attr('class', 'display_box');
$(curr).next().attr('class', 'display_box current');
}
else{
$('#suggest li:first-child').attr('class', 'display_box current');
}
}
if(e.keyCode==38)
{
if(curr.length)
{
$(curr).attr('class', 'display_box');
$(curr).prev().attr('class', 'display_box current');
}
else{
$('#suggest li:last-child').attr('class', 'display_box current');
}
}
if(e.keyCode==13)
{
var search_terms = $('.current a').text();
// perform a search with this text...
doSearch(search_terms,true,false);
//update the search textbox
$('#searchbox').val(search_terms);
}
})
And don't forget to delete the previous code at the bottom...

Categories