Hi. i am trying to show a hidden element using a button. but i want to make it so that everytime the button is clicked the hidden element get shown that same amount as button clicked.

example:

<input type="button" value="Click me" id="clickme">
<input type="text" id="textbox">

<script>
    $(document).ready(function()
    {   
        var element = $("#textbox").hide();
        var count = 0;
        $("#clickme").on("click", function()
        {
            count++;//count button clicked
            var elem = element.clone();
            //then the element will be cloned same amount as button click, stuck here
        });
    });
</script>

well I'm stuck there. is the approach wrong? do i use a loop or something? TIA

Recommended Answers

All 2 Replies

Why not do something like this?

<input type="button" value="Click me" id="clickme">
        <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
    $(document).ready(function()
    {
        var element = '<input type="text" id="textbox">';
        var count = 0;
        $("#clickme").on("click", function(event)
        {
            event.preventDefault();
            count++;
            $(element).insertAfter('#clickme');
        });
    });
</script>

If you need explanation on what is wrong with your code:
- you did a hide of your element on line 7
- you've put an onClick event but that was equal to a submit... which I think results in a page refresh
- you've cloned your element (hidden element), but you didn't append it to your html.

Regarding my code, you don't actually have to count the times a button is pressed so you can eliminate count = 0; and count++; lines (unless you really need them).

The first time the button is clicked you're going to clone it once?
The second time the button is clicked you're going to show it twice? And so on?

Then, it sould be something like:

$(function()
    {   
        var element = $("#textbox").hide();
        var count = 0;
        $("#clickme").on("click", function()
        {
            count++;
            for(var i=0;i<count;i++) {
               element.clone().insertAfter("#clickme");
            }
        });
    });

This way, at the third click, there'll be 6 elements (1 for the first click, 2 for the second, 3 for the third).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.