Asdfasf

Thursday, February 28, 2013

Creating Dynamic HTML form with JQuery

In following sample, we will generate form elements dynamically according to provided html snippet in text area. I do nothing, jquery does all job :), thanks to it.
When user enters html form elements in text area and submit "Add html code entered in text are to form" button, form elements will be generated dynamically.


When user clicks on "Submit" button, form elements will be sent with GET method to google :) :
https://www.google.com/?education=HighSchool&TofD=Day

Here is html code, you have to download jquery and put it next to this html file.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
</head>

<body>
<script src="jquery-1.9.1.js"></script>
 <script>
$( document ).ready(function() {
 $("#add").click(function( event ){
  $("#formdiv").html("");

  htmlcode = document.getElementById("htmlcode").value;

  $("#formdiv").html(htmlcode);
 });
});


</script>

<textarea rows="4" cols="50" id="htmlcode"></textarea>
<br/>
<input name="add" type="button" value="Add html code entered in text area to form" id="add"/>

<br/>
SUBMISSION FORM:
<table border=1>
<tr><td>

<form method="get" action="http://www.google.com">
<div name="formdiv" id ="formdiv"></div>
<input type="submit" value="Submit"/>
</form>

</td></tr>
</table>
</body>
</html>

No comments: