Nuju Nuju - 3 months ago 9
HTML Question

How to get form html() via jQuery including <form></form> tag?

I want to display my form html content into a textarea which allows the user to edit form elements via user interface. Here is my form,

<form name="myform" action="abc.php">
<input type="radio" name="radio1" value="1" checked>
<input type="radio" name="radio2" value="2"><br><br>
<input type="text" name="input" value="My Name" />
</form>


I tried below code, but it display's the form elements only (not includes the form tag).

<script>
$(document).ready(function()
{
$('a').on('click', function() {
$("input,select,textarea").each(function() {
if($(this).is("[type='checkbox']") || $(this).is("[type='checkbox']")) {
$(this).attr("checked", $(this).attr("checked"));
}
else {
$(this).attr("value", $(this).val());
}
});
alert($('form').html());
});
});
</script>


Above code alerts an output like below,

<input type="radio" name="radio1" value="1" checked>
<input type="radio" name="radio2" value="2"><br><br>
<input type="text" name="input" value="My Name" />


But I need an output like below,

<form name="myform" action="abc.php">
<input type="radio" name="radio1" value="1" checked>
<input type="radio" name="radio2" value="2"><br><br>
<input type="text" name="input" value="My Name" />
</form>

Answer

I hope you can use these function for form $("form").clone().appendTo("body"); else use

<div id='formdiv1'>
<form name="myform" action="abc.php">
<input type="radio" name="radio1" value="1" checked>
<input type="radio" name="radio2" value="2"><br><br>
<input type="text" name="input" value="My Name" />
</form>
</div>

alert($('#formdiv1').html());