Highlight The Contents Of A Textarea With JavaScript

×

Error message

Warning: apc_store(): Potential cache slam averted for key 'www.hashbangcode.com::cache_bootstrap::variables' in DrupalAPCCache->set() (line 206 of /var/www/www.hashbangcode.com/2014-03-22-2105/docroot/sites/all/modules/contrib/apc/drupal_apc_cache.inc).

Wednesday, August 27, 2008 - 09:47

If you want to give your users a little snippet of code it is nice to give them the option of selecting the entire block of code without having to highlight the text manually. This can be done with a simple JavaScript button.

Take the following form:

1
2
3
4
5
<form name="aForm">
<textarea name="aTextarea" cols="50" rows="20">
Copy this text onto your own website.
</textarea>
</form>

To enable the selection functionality you just need to add in an input button. The click event of this button will be to run a JavaScript bookmarklet that focuses on the textarea in question (in this case it is called aTextarea) and selects the text.

1
2
3
4
5
6
7
<form name="aForm">
<textarea name="aTextarea" cols="50" rows="20">
Copy this text onto your own website.
</textarea>
<br />
<input type="button" value="Highlight All" onclick="javascript:this.form.aTextarea.focus();this.form.aTextarea.select();" />
</form>

The user can then copy the text as they normally would.

Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Add new comment