Additionally, this can also be achieved by just using someDiv.innerHTML
.
#!javascript
var formDiv = document.getElementById('my_form_div'); // you hopefully have a better method to do this ;)
if (formDiv) {
var HTML = '<form method="GET" action="?submit" onsubmit="return !formSubmitted()">';
HTML += '<input type="text" name="field1" />';
HTML += '<input type="text" name="field2" />';
HTML += '<input type="submit" value="go" />';
HTML += '</form>';
formDiv.innerHTML = HTML;
}
Note the function formSubmitted()
. This one gets called right when the user submits the form, you can then do anything you want in JS, like submitting the form values via AJAX, and if you return true (e.g. when you handled the form successfully in JS), the true gets inverted to false and the form will not submit via browser. If the user has JS deactivated, the form will just be submitted by the browser the standard way.
The advantage of this is that you can get the desired form HTML via AJAX, generated by PHP, and you can put the exact same HTML inside < noscript >
tags, for those with deactivated JS, by calling the same PHP function to get the HTML:
... some HTML
<div id="my_form_div">
<noscript>
<?= myFormHTML() ?> # equal to: <?php echo myFormHTML() ?>
</noscript>
... more HTML