Isn’t it nice when you can click a textarea and have javascript immediately select the content so you can quickly copy and paste it? I think so. First we create our javascript function. Because I’m using WordPress to host my site for now, I needed to declare this function in an external javascript file named highlight.js. You could just as easily declare this function in the HTML or PHP file if you’re not using WordPress.
function highlight(name) { var text_val=eval("document." + name + ".type"); text_val.focus(); text_val.select(); }
Next, we want to actually use this function in whatever file we’re using it in. Remember that because I’m using WordPress I had to define this function in an external file named highlight.js, so now we simply have to include it in the post or page with the following script tag. I usually place these types of script declarations at the top of my post or page to keep track of them.
<script language="javascript" src="../../highlight.js"></script>
Finally, the actual usage while coding. Study the example – its worth a thousand words.
<form name=form_one method=post action=''''> <pre> <textarea name=type onClick="highlight('form_one');" READONLY> *This text will get highlighted on click* </textarea> </pre> </form>
There is one main thing to note. Notice that I pass in the name of the form as a parameter to the highlight() function. This is so the javascript code can parse the HTML and find exactly which form to highlight on click. If you change the name of this form or add additional forms, make sure you update the highlight() function’s parameter.
Additionally, notice the READONLY tag in the textarea declaration. This is just to prevent users from accidentally deleting the highlighted content – just a small touch that can save some one some time some where.
