jab
jab

Reputation: 5823

Need Help Creating Form Elements Based On Click via JavaScript and JQuery

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>

Upvotes: 2

Views: 413

Answers (3)

Amir Ismail
Amir Ismail

Reputation: 3883

first you don't have any tag with id area so it will generate error when trying get it

I think you do it with hard way check this demo it more simple than what you do

Upvotes: 0

karim79
karim79

Reputation: 342635

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.

Upvotes: 3

nnnnnn
nnnnnn

Reputation: 150010

This line:

var ni = document.getElementById('area'); 

will set ni to null, because you don't have any elements with an Id of 'area'. Which means later in the function when you try to say:

ni.appendChild(newdiv); 

it won't work.

Incidentally, why are you creating the extra div elements to hold the new inputs? Why not just add input elements directly?

Upvotes: 0

Related Questions