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?

3 Answers 3

11

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)

Sign up to request clarification or add additional context in comments.

4 Comments

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.
Yes, I will definitely do that :) With raw HTML I think the security will have to be stronger.. :-/
A good start for that might be this question stackoverflow.com/questions/3452322/… I made one solution but it's in C#, but you can get some idea from that and convert to php.
What should i do to get the data-attributes along with html ?
4

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

var myHTML = document.getElementById('new_form').innerHTML;

2 Comments

Thanks! I tried but I get null for the var. but $(".new_form").html() works
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.
4

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

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.