ci_lover
ci_lover

Reputation: 718

How to loop through all elements jQuery

I have images and have to count facebook shares for each image. I can't make loop for that. It's now for only one element. How to do that? My code is:

        <script>
        $(document).ready(function(){
        	var current = 0;
        	$count = $('#count_bombs').val();
        	$('#' + current).each(function() {
        		var id = $('#' + current).val(); console.log(id);
        		$.getJSON('https://graph.facebook.com/http://example.com/images/view/' + id, function(data) { 
        		   document.getElementById("shares_count_" +current).innerHTML = data.shares;
        		  console.log(data.shares);  console.log("#shares_count_" +current);
        		});
        		current++;
        	});

        });
        </script>
        <?php $num=0;  $id = 0; ?> 
        		<?php foreach($images as $key=>$val){  ?>
        <div>
        <a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo URL::base();?>images/view/<?php echo $val['image_name'];?>">
        <span aria-hidden="true"  class="glyphicon glyphicon-link"></span>
        	<input type="hidden" id="<?php echo $id; ?>" class="count" value="<?php echo $val['image_name'];?>">
        	SHARE	
        </a>
         </div>

        <div>
       <span class="glyphicon glyphicon-comment" aria-hidden="true" ></span> 
        	<span id="shares_count_<?php echo $id; ?>"></span>
        	<input type="hidden" value="<?php echo count($bombs);?>" id="count_bombs" name="count_bombs">
       </div>

Edited: I did it. I used index parameter of each method. This is my code:

<script>
$(document).ready(function(){
	var current = 0;
	$("input[type=hidden]").each(function(index, element){
		var id = $('#' + current).val();
		$.getJSON('https://graph.facebook.com/http://pbombd.dev/bombs/view/' + id, function(data) { 
		   $('#shares_count_' + index).html(data.shares);
		});
		current++;
	});

});
</script>

Upvotes: 0

Views: 97

Answers (1)

Magus
Magus

Reputation: 15104

$('#' + count) will returns only one element so can't loop on it. It seems like you want to find every hidden input with the css class count in your page. You can do it like this :

$('input.count').each(function() {
    $input = $(this);

    // $input contains the hidden input
    console.log($input.attr('id));
});

Upvotes: 1

Related Questions