I'm working on a website where users can create and save their own HTML forms. Instead of inserting form elements and ids one by one in the database I was thinking to use js (preferably jquery) to just get the form's HTML (in code source format) and insert it in a text row via mysql.
For example I have a form in a div
<div class="new_form">
<form>
Your Name:
<input type="text" name="something" />
About You:
<textarea name=about_you></textarea>
</form>
</div>
With js is it possible to get the raw HTML within the "new_form" div?
I'm working on a website where users can create and save their own HTML forms. Instead of inserting form elements and ids one by one in the database I was thinking to use js (preferably jquery) to just get the form's HTML (in code source format) and insert it in a text row via mysql.
For example I have a form in a div
<div class="new_form">
<form>
Your Name:
<input type="text" name="something" />
About You:
<textarea name=about_you></textarea>
</form>
</div>
With js is it possible to get the raw HTML within the "new_form" div?
Share Improve this question edited Aug 27, 2010 at 0:13 VolkerK 96.2k20 gold badges167 silver badges231 bronze badges asked Aug 26, 2010 at 23:57 Cyber JunkieCyber Junkie 7666 gold badges16 silver badges31 bronze badges3 Answers
Reset to default 11To get all HTML inside the div
$(".new_form").html()
To get only the text it would be
$(".new_form").text()
You might need to validate the HTML, this question might help you (it's in C# but you can get the idea)
Yes, it is. You use the innerHTML property of the div. Like this:
var myHTML = document.getElementById('new_form').innerHTML;
Note when you use innerHTML
or html()
as above you won't get the exact raw HTML you put in. You'll get the web browser's idea of what the current document objects should look like serialised into HTML.
There will be browser differences in the exact format that comes out, in areas like name case, spacing, attribute order, which characters are &
-escaped, and attribute quoting. IE, in particular, can give you invalid HTML where attributes that should be quoted aren't. IE will also, incorrectly, output the current values of form fields in their value
attributes.
You should also be aware of the cross-site-scripting risks involved in letting users submit arbitrary HTML. If you are to make this safe you will need some heavy duty HTML ‘purification’.