views:

58

answers:

3

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?

+7  A: 

To 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)

BrunoLM
I mean to get the HTML source code, sorry.
Cyber Junkie
Then it's the first code line
BrunoLM
Awesome it works! Thanks!
Cyber Junkie
As a sidenote, I'd recommend doing some validation/sanitization of the HTML on the back-end to make sure nothing malicious is being added to the form code by nefarious users. The security importance of this will depend on your audience.
calvinf
Yes, I will definitely do that :) With raw HTML I think the security will have to be stronger.. :-/
Cyber Junkie
A good start for that might be this question http://stackoverflow.com/questions/3452322/method-to-strip-html-tags-not-in-a-safe-list I made one solution but it's in C#, but you can get some idea from that and convert to `php`.
BrunoLM
+1  A: 

Yes, it is. You use the innerHTML property of the div. Like this:

var myHTML = document.getElementById('new_form').innerHTML;
Hammerite
Thanks! I tried but I get null for the var. but `$(".new_form").html()` works
Cyber Junkie
whoops, your div has "new_form" as a class rather than as an id. getElementById will work only when the Id of the element is specified.
Hammerite
Oooh! I see, thanks! :)
Cyber Junkie
+1  A: 

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’.

bobince
Thank you for sharing that! I'll have to do some changes.
Cyber Junkie