0

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

Edited by nadiam

3
Contributors
2
Replies
27
Views
2 Years
Discussion Span
Last Post by AleMonteiro
0

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

Edited by Adrian_5: more explanations

0

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.