Jack Coolen Jack Coolen - 3 months ago 7
Javascript Question

Click a button 5 times on page load

I have something really basics here. I have a button, the idea is to click it so that it adds one field at a time dynamically. But when the page load, I want it to click the button automatically to place 5 fields by default and then afterwards I should still be able to add extra field if necessary.

This is what I so far have, but it adds 5 fields as soon as I click it. I don't want that.

<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://code.jquery.com/jquery-3.1.0.min.js" integrity="sha256-cCueBR6CsyA4/9szpPfrX3s49M9vUU5BgtiJj06wt/s=" crossorigin="anonymous"></script>
</head>
<body>
<div id="container"></div>
<button id="somebutton">Click</button>

<script type="text/javascript">
$(document).ready(function() {
for (var counter = 0; counter < 5; counter++) {
$("#somebutton").click(function () {
$("#container").append('<div class="module_item"><input type="text" /></div>');
});
}
});
</script>
</body>
</html>


Please note that this is the only way how I want it. On page load, button gets clicked automatically 5 times to add 5 fields. Then I can manually click it afterwards to add a sixth, seventh, and so on field.

Answer

Just a minor reorganization to your code:

        $(document).ready(function() {
              $("#somebutton").click(function () {
                    $("#container").append('<div class="module_item"><input type="text" /></div>');
              });
              for (var counter = 0; counter < 5; counter++) {
                  $("#somebutton").click();
              }
        });
Comments