Hi, I'm a web developer and blogger from Russia. My nickname is Dimox.
Sorry for my English, it's not my native. Read more about me and my blog.

jQuery: Switching The Focus Between Two Form Fields

jQuery: Switching The Focus Between Two Form Fields

In the last version of my Google Translator widget for Opera I had to solve one problem – how to switch the focus between two textareas by clicking on a hotkey.

In this article I want to share jQuery script, that solves this problem. May be it will be usefull for someone.

What is interesting, while I wrote this post and have tested the script, I reduced its size about 2.5 times compared with the original version (this suggests that the same problem can be solved in different ways and always need to try to optimize JavaScript scripts).

Now lets look at the script:

$(function() {

	/* Adding a class to TEXTAREA to determine the focus */
	$('textarea').focus(function() {
		$('textarea').removeClass('hasFocus');
		$(this).addClass('hasFocus');
	})

	/* Putting the focus by default on a first TEXTAREA */
	$('#textarea1').focus();

	/* Switching the focus by clicking Enter */
	$(document).keypress(function(e) {
		if(e.which == 13) {
			$('textarea').not('.hasFocus').focus();
			return false;
		}
	})

})

What we doing in this script? We add the .hasFocus class to the focused textarea, remove this class from a field that is not focused, and while pressing Enter focus switches to a textarea, that has no this class.

May be there is a shorter way to do the same, but, unfortunately, I not found simpler way to get a field, that has not the focus.

Demo

Look at the script in action.

Lеаvе а Соmmеnt

© 2009–2016 Dimox.net  •  Privacy Policy