Create dynamic div with jquery
Im trying to create a button that generates already formated divs everytime it is pushed.
The divs are composed by forms and their fields should already be filled with data that is stored in variables in javascript.
eg.
<div id="myDiv_#">
<form id="myForm">
<input type="text" id="start_date" name="start_date" value="someJavascriptVariable" />
<input type="text" id="end_date" name="end_date" value="someJavascriptVariable" />
<select name="type" id="type">
<option value="1">"someJavascriptVariable"</option>
<option value="2">"someJavascriptVariable"</option>
</select>
<input type="button" id="new_button" value="Show">
</form>
</div>
<script>
$('#button_push').click(function()
{
//creating myDiv_#
}
</script>
I was searching arround web, but never found good results :s Im asking you help with this, maybe a guide line or a start point. The point is, everytime user push the button, a new div is created with parameters above.
Cheers
With markup as complex as that it's probably easier if have a hidden version of it which you can clone, amend attributes of then append to the page as required.
Something like this:
<div id="container"></div>
<div style="display: none;">
<div id="myDiv_#">
<form id="myForm">
<input type="text" id="start_date" name="start_date" value="someJavascriptVariable" />
<input type="text" id="end_date" name="end_date" value="someJavascriptVariable" />
<select name="type" id="type">
<option value="1">"someJavascriptVariable"</option>
<option value="2">"someJavascriptVariable"</option>
</select>
<input type="button" id="new_button" value="Show">
</form>
</div>
</div>
$('#button_push').click(function() {
var $div = $("#myDiv_#").clone(true); // keep events'
$div.attr('id', '').addClass('clone'); // example of amending attributes
$("#container").append($div); // append
});
Example fiddle
You can easily replace the someJavascriptVariable
strings with the specific variable relevant to that clone instance too.
下一篇: 用jquery创建动态div