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> </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.

7

3 Answers

you can put it into tag using 'onload' event:

<body onload='yourfunction()'> 

or just use jQuery:

$(document).ready(function() { yourFunc(); }); 

I suppose you could use <body onload="yourfunction()"> you also should look into .

As you can see there are quite a few events available in javascript one should allways pick the right tool(event) for doing the work.

If you want to call jquery function on Page load: you can use $(document).ready(function(){});

For example:

Jquery-

<script type="text/javascript"> $(document).ready(function(){ createinputprice(); }); </script> 

and you can also fire the click event in Jquery:

HTML-

<a href='#' onclick="createinputprice();">Add Price</a> 

Jquery-

 <script type="text/javascript"> $(document).ready(function(){ $('#myLink').click(); }); </script> 
3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.