Categories:

Home / Free JavaScripts / Forms / Here

Cut & Paste HTML to Entities (form) script

Credit: JavaScript Kit

Description: This script converts special HTML characters to their entities version inside user entered data such as a TEXTAREA before the form is submitted. Specifically:

  • '<' becomes '&lt;'
  • '>' becomes '&gt;'
  • '"' (double quote) becomes '&quot;'
  • ''' (single quote) becomes '&#039;'
  • '&' becomes '&amp;'

This helps prevent potentially harmful or disruptive HTML tags from being posted to your form.

See also: Strip HTML Tags (form) script

Example:


Directions: Simply add the below script into the <BODY> section of your page:

<script type="text/javascript">

// HTML to Entities (form) script- By JavaScriptKit.com (http://www.javascriptkit.com)
// For this and over 400+ free scripts, visit JavaScript Kit- http://www.javascriptkit.com/
// This notice must stay intact for use

function html2entities(){
var re=/[(<>"'&]/g
for (i=0; i<arguments.length; i++)
arguments[i].value=arguments[i].value.replace(re, function(m){return replacechar(m)})
}

function replacechar(match){
if (match=="<")
return "&lt;"
else if (match==">")
return "&gt;"
else if (match=="\"")
return "&quot;"
else if (match=="'")
return "&#039;"
else if (match=="&")
return "&amp;"
}

</script>

<form onSubmit="html2entities(this.data1, this.data2)">
<textarea name="data1" style="width: 400px; height: 100px"></textarea><br />
<textarea name="data2" style="width: 400px; height: 100px"></textarea><br />
<input type="submit" value="submit">
</form>

To demonstrate how to use this script with the desired form elements, lets use the sample form included in the code:

<form onSubmit="html2entities(this.data1, this.data2)">
<textarea name="data1" style="width: 400px; height: 100px"></textarea><br />
<textarea name="data2" style="width: 400px; height: 100px"></textarea><br />
<input type="submit" value="submit">
</form>

The part in red is what you'll need to add to your form. "this.data1" and "this.data2" corresponds to the names of the applicable form elements. You can enter as many form elements as you wish- simply separate each one with a comma.


Copyright © 1997-2014 JavaScript Kit. NO PART may be reproduced without author's permission.