Need help creating JavaScript-based form elements via JavaScript and JQuery

advertisements

I'm pretty new to web programming and I am trying to simply add text fields to a certain form based upon clicking a previous text field. The html page will start with one field and will grow with text fields based upon clicking any previous field. This is via client-side JavaScript.

However, it seems like the code isn't working and I'm not getting anywhere. All that shows up is one text field regulated by the HTML and the click event is outputting anything. You can ignore the styling for right now.

<!DOCTYPE html>
<html>
<title>This is just a test</title>
<script type="text/javascript"  src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
$(document).ready(function(){
var inival = 0;
function addTextBox()
{
    var newArea = add_New_Element();
    var htcontents = "<input type='text' name='textbx[]'/>";
    document.getElementById(newArea).innerHTML = htcontents; // You can any other elements in place of 'htcontents'
}
function add_New_Element()
{
inival=inival+1; // Increment element number by 1
var ni = document.getElementById('area');
var newdiv = document.createElement('div'); // Create dynamic element
var divIdName = 'my'+inival+'Div';
newdiv.setAttribute('id',divIdName);
ni.appendChild(newdiv);
return divIdName;
}
  $("input").click(function(){
    addTextBox();
  });
});
</script>
<body>
<div>
<form id="mainform" action="execute.php" method="post">
<input type="text" name="textbx[]"/>
</form>
</div>
</body>
</html>


You can replace your entire solution with this:

$("input").click(function() {
    $(this).after($(this).clone(true));
    $(this).after("<br />");
});

Demo.

I would prefer to use .delegate and not bother cloning the event handlers:

$("#myForm").delegate("input", "click", function() {
    $(this).after($(this).clone());
    $(this).after("<br />");
});

Demo.