Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Javascript Loop only return the last value when using .empty function

javascript jquery

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1 keanallen

keanallen

    CC Newcomer

  • Member
  • PipPip
  • 18 posts

Posted 13 May 2015 - 10:09 AM

Please help me out on this problem. What I want to do is to append the data only into a specific ID for example to the ID #myId:

setInterval(sample, 2000);
 function sample()
 {
   for(var i=0;i<=3;i++)
     {
         $('.found .find').each(function() {
             if(this.id == "myID")
              {
                // if the ID of this element is equal to #myID
                // this is the place where the data will append
                $(this).empty();
                $(this).append(i);
              }
         });
     }

 }

MY HTML

<div class="found">
      <div class="find" id="myID"></div>
</div>

 <div class="found">
      <div class="find" id="anID"></div>
</div>

<div class="found">
      <div class="find" id="anID2"></div>
</div>

It works for me but it ONly prints THe last value of the loop which is 3. When I remove the .empty() it will not stop in appending data



#2 lespauled

lespauled

    CC Leader

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1360 posts

Posted 13 May 2015 - 11:03 AM

It's bad practice and extremely bug prone to create functions inside a loop.

 

Of course it prints the last value, you are emptying it every call.

 

As a proof of concept, try the following:

$(function () {

    var x=0;

    setInterval(sample, 2000);

    function sample() {
            $('.found .find').each(function () {
                if (this.id == "myID") {
                    // if the ID of this element is equal to #myID
                    // this is the place where the data will append
                    $(this).empty();
                    $(this).text(x);
                }
            });
        
        x = x + 1;

    }
});

My Blog: http://forum.codecal...699-blog-77241/
"Women and Music: I'm always amazed by other people's choices." - David Lee Roth

#3 Vaielab

Vaielab

    Programming God

  • Expert Member
  • PipPipPipPipPipPipPip
  • 1382 posts

Posted 13 May 2015 - 07:52 PM

My question is why aren't you using the id directly in the search like so

$('.found .find#myId').each(function() ...

 

And since id are supposed to be unique on a page a simple $('#myId') should be enough


Edited by Vaielab, 13 May 2015 - 07:53 PM.

You can now stalk me on linkedin: http://ca.linkedin.c...elle/24/b44/88/ !





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download