I am working on a javascript plugin for a website where I have to add a form to a certain panel of the page. I was wondering if there was any way to import/read an html file(it contains the html code for the form) into a javascript file rather than creating a bunch of HTML Elements to create the form.
1 Answer
If using jQuery, you can insert the HTML as a string using the append, insertAfter, and similar methods (note that the template string syntax only works on ECMAScript6 compatible browsers).
$('#addForm').click(function() { // execute the following with #addForm is clicked
$('#formPanel').append( // add the following to the innerHTML of #formPanel
// backtick starts a template string
`
<form action='sumbit.php' method='POST'>
First name: <input name='first'>
Last name: <input name='last'>
<input type='submit'>
</form>
`);
});
6 Comments
NewToJS
This wouldn't work. Also jQuery isn't tagged in the question. Tip: if you want to give a solution / answer to question with no current source code, I would recommend you put commend in the source code and give a detailed description of what is happening in the code but most important is to debug your answer to make sure it will work. (This won't)
Kwarrtz
@NewToJS Yes, the string syntax error was a careless mistake which I have now corrected. As for the jQuery, the asker did not state that they wanted a vanilla Javascript solution either. To me, it seems unreasonable to avoid any library or or framework which is not explicitly stated as an "acceptable solution". If the asker knew exactly which libraries and frameworks were necessary to achieve the desired result, it is unlikely they would be asking the question here rather than reviewing documentation.
NewToJS
Users can tag the languages, jquery maybe javascript but it has it's own tag as some users like to use pure javascript and not jQuery. Some users also run javascript offline and don't wish to download the jQuery file so if jQuery isn't tagged then it would be a good idea to ask in the comments section before hand. Also showing how to use jQuery (link to the library) would be a good idea as some people might not know how to do it, hence being a reason for jQuery not being tagged. Since you have fixed the syntax error I have removed my down vote as that was the reason I added mine.
NewToJS
I would still recommend comments in the source code or detailed description to explain to the OP what it is your source code is doing. Maybe some reference links for the OP to look at to help explain the jQuery...
Kwarrtz
@NewToJS, As per your suggestions, I have added comments and links to documentation.
|
innerHTML/outerHTMLon some element to let the browser parse it... but I'm not sure that's what you want.