0

I'm new to JavaScript so please be patient with me.

I'm currently fiddling with this code:

$("input[type = submit]").click(function(){
        $("<div>").attr("class","apples").html(itemInput.value).appendTo(".div1");
        $("<button>").appendTo(".apples");

            clearInput();
    })

basically it adds a button along with a div when you click submit. But its adding more buttons than div. For example. Pressing submit once gives me 1 div, and 1 button (which is what I want), pressing submit the 2nd time, gives 1 div and 2 buttons. pressing submit the 3rd time, gives me 1 div and 3 buttons. The more I press submit the more buttons will spawn with a single div.

I was wondering how I can just make it 1 div with 1 button attached to it once created.

Edit: HTML: This is basically the whole thing. excluding <head>.

<body>
<div class = "centerAlign" >
    <div class = "div1">
        <input id="itemInput" type="text" placeholder="add to-do items " />
        <input type="submit" value="ADD"/>
    </div>
</div>  

<script>
    $("input[type = submit]").click(function(){
            $("<div>").attr("class","apples").html(itemInput.value).appendTo(".div1");

        $("<button>").appendTo(".apples");

        }
            clearInput();
    })
    function clearInput(){
    itemInput.value = "";
    }
  </script>
  </body>
 </html>
1
  • can you post your html as well please Commented Oct 24, 2016 at 23:23

4 Answers 4

2

If you want appear button to last created div with class apples this could be the way:

$("input[type = submit]").click(function(){
    $("<div>").attr("class","apples").html(itemInput.value).appendTo(".div1");
    $("<button>").appendTo($(".apples").last());

        clearInput();
    }); 

With the last() function you get the last element from DOM.

Here I created Fiddle i hope it help https://jsfiddle.net/Lyt3otrp/

Wish you luck ;]

Sign up to request clarification or add additional context in comments.

1 Comment

@OrangePineapple I am glad it help.
1

That is because every time you are clicking the submit button,,

$("<button>").appendTo(".apples"); is running, which means its gonna append a button every time the submit button is clicked.

so you should simply check if you already added the button to div or not,, if yes then simply ignore the line and if no then run the line.

Example:

var i=0;
$("input[type = submit]").click(function(){
            $("<div>").attr("class","apples").html(itemInput.value).appendTo(".div1");

              if(i==0){ 
                  $("<button>").appendTo(".apples");
                  i=2;
              } 

            clearInput();
})

That's one way of doing things :) Good luck.

Comments

1

You may be getting classes mixed up with IDs in this case. It's an easy thing to do, especially when new to jQuery or CSS (since the selectors are very similar). The primary difference between classes and IDs is that classes can apply to many elements on a page, where IDs only apply to one element (and should never apply to multiple elements on one page).

That being said, you are adding a class of apples to a div, then appending a button to all elements with a class of apples (first click, there is only one - the newly created one), then appending that .apples element to the page. Be wary that $('.apples') is selecting all .apples elements. So the second time you click, you are appending to the first .apples element that was created, plus the new one you are creating.

To resolve the situation, either add IDs to the element (longer, more difficult route, though not very difficult by any means), or more elegantly, you can append the button as you're generating your new .apples element. Since I'm not sure of your end-game here, I will add some bogus functionality (a reason for the buttons to be there). I'm going to use them to remove the .apples element that they are a child of, though you could change their functionality to fit your needs.

We'll start with some basic HTML:

<button id='add'>Add Apples</button>
<input id='input'>
<div id='container'></div>

I think my #container may correspond with your .div1, but I'm not sure without seeing your HTML code. In any case, we can proceed with the JavaScript (and jQuery) portion:

$('#add').click(function() {
  //gather input data
  var num = $('#input').val();
  //validate input data
  if(num == '' || isNaN(num)) { 
    alert("Please enter a numerical value.");
    $('#input').focus();
    return false; 
  }
  //manipulate input data
  $('<div>', {class:'apples'}).append(
    num,
    '<br>',
    $('<button>',{text:'-'}).click(function() {$(this).closest('.apples').remove(); })
  ).appendTo('#container');
  //clear the input field
  $('#input').val('');
});

Here's a jsFiddle link so you can review to see it in action: (NOTE: I added validation to the input field, you MUST add a number to click Add Apples) https://jsfiddle.net/jezztutz/

What's happening is, on the button click (Add Apples, or #add) we gather the numerical input (or supposed to be numerical in my case), validate that it's not empty and is, in fact, a number (if not, error out). Then we generate a div on the fly, append that number to it, append a horizontal break, and finally append a button directly to that element (no more of that selecting multiple elements nonsense). We can then append that .apples div, complete with button, to the #container div (in my example), and clear out the input field to start anew.

1 Comment

Thank you so much.
1

your problem is that you add the button to all the "apples" that you have created every time. I think this what you are looking for:

<body>
<div class = "centerAlign" >
    <div class = "div1">
        <input id="itemInput" type="text" placeholder="add to-do items " />
        <input type="submit" value="ADD"/>
    </div>
</div>  

<script src="js/jquery.min.js"></script>
<script>
    var counter = 0;
    $("input[type = submit]").click(function(){
        counter++;
        $("<div>").attr("class","apples num" + counter).html(itemInput.value).appendTo(".div1");
        $("<button>button" + counter + "</button>").appendTo(".num" + counter);
        clearInput();
    })

    function clearInput(){
        itemInput.value = "";
    }
</script>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.