views:

71

answers:

4

Hi All,
I am trying to create a form using only JavaScript. I mean create a form for a web page, add elements to it, set their values and submit the form.
Moreover, if JS is disabled in the browser the normal HTML form should get submitted.

Is there any way to achieve this?

Thank You All.

+2  A: 

Have a normal HTML form, hide it with JS. A good way to do that with no flicker is:

<body>
  <script type="text/javascript">
    document.getElementsByTagName('body')[0].className = "js"
  </script>
  <style type="text/css">
    body.js #no_javascript_form { display: none; }
  </style>
  <form id="no_javascript_form">...</form>
</body>

Then create the <form> dynamically. With jQuery you can do:

<div id="form_placeholder"></div>
<script type="text/javascript">
  $('#form_placeholder').append(
    $('<form/>')
      .append('<input type="text"/>')
      .append('<button type="submit">submit</button>')
  );
</script>
orip
A: 

You could also easily add the html for the form via javascript using something like jQuery's append method

Whisk
+1  A: 
var input = document.createElement('input');
    input.name = 'generated_input';
    document.getElementbyId('inputs_contained').appendChild(input);

See here - http://stackoverflow.com/questions/1251086/adding-new-text-box-using-javascript

Pino
+1  A: 

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
Pascal