Tag Archives: select all

jQuery + Javascript: How to Select all Text in a Textbox CodeUnit 10 MAY 2010

I have a nice little inline editing function attached to one of my administrative pages which basically lists a whole lot of tag names currently saved on the system.

When you click on the tag name, it gets replaced by a textbox containing the name, allowing you to edit and then save your changes.

In order to make the experience a little more streamlined, I wanted to set it up so that when clicking on the tag name the text box should appear directly in its place, with all the characters in the textbox highlighted (i.e. selected) and with browser focus firmly on the box.

Achieving this turns out to be pretty simple.

Basically, plain old vanilla JavaScript already gives us the functionality to focus on an input element as well as select all characters in that element. So, we stuff that into its own little function:

function selectAllText(textbox) 





We then attach this function to the moment the textbox appears in place of the original label, binding it to the click event of the label element:






There, all done! (Now wasn’t that nice and simple stuff?)

jQuery: Checking or Unchecking All Checkboxes CodeUnit 08 APR 2010

Providing functionality to check all, uncheck all or even to invert the checkboxes currently selected on a page is pretty simple to achieve with either plain old JavaScript or the newer, more flashy jQuery library. Important too if you think just how much more usable your site becomes with these handy shortcuts available to the user.

Now to select all checkboxes on a page and then check them, one simply has to make use of the handy INPUT[type=’checkbox’] jQuery selector call and then follow that up with an attr call in order to change the checked attribute status to true. Finally, you bundle this all up and apply it to the click event of some handy button or span and end up with this:

	$("INPUT[type='checkbox']").attr('checked', true);

Similarly to untick all checkboxes on your page you would go with something like this:

	$("INPUT[type='checkbox']").attr('checked', false);

The final little piece of magic on display for today is the function to invert the current checkbox tick selection. Basically here we are going to scroll through each checkbox using jQuery’s handy each function and set the checked attribute accordingly based on its currently held value, which in code would look something like this:

        	if (this.checked == false) {
			this.checked = true;
		} else {
			this.checked = false;

Deceptively simple, was it not? :P