I have a Javascript function for creating new form elements on a web page. The function is called by an onclick event.
I can't figure out how to run the function without the onclick event. I need to do this as I have Python code generating content to prepopulate the form elements, but still wish to be able add and remove the form elements dynamically with the Javascript.
Javascript function:
pcount = 0;
createinputprice =function (){
field_area = document.getElementById('pricetable');
var tr = document.createElement("tr");
var cella = document.createElement("td");
var cellb = document.createElement("td");
var input = document.createElement("input");
var input2 = document.createElement("input");
input.id = 'descprice'+pcount;
input2.id = 'actprice'+pcount;
input.name = 'descprice'+pcount;
input2.name = 'actprice'+pcount;
input.type = "text";
input2.type = "text";
cella.appendChild(input);
cellb.appendChild(input2);
tr.appendChild(cella);
tr.appendChild(cellb);
field_area.appendChild(tr);
//create the removal link
var removalLink = document.createElement('a');
removalLink.onclick = function(){
this.parentNode.parentNode.removeChild(this.parentNode)
}
var removalText = document.createTextNode('Remove Field');
removalLink.appendChild(removalText);
tr.appendChild(removalLink);
pcount++
}
HTML:
<table id="pricetable">
</table>
<a href='#' onclick="createinputprice()">Add Price</a>
<script type="text/javascript">
createinputprice();
</script>
The onclick event works fine in JSFiddle but calling the function directly doesn't work at all.