prajan
prajan

Reputation: 189

For loop in jQuery. How to?

How can I replace this for-each loop with jQuery?

$(document).ready(function(){
    hidebutton = $("#hideall");
    hidebutton.click(function(){
        for(i=1;i<=6;i++){
                var countrylist = document.getElementById("Country-"+i);
                countrylist.style.display = "none";
            }
    });
});

The HTML is

<input id="hideall" type="button" value='Hide Countries' /><br /><br />
<div id="Country-1">USA</div>
<div id="Country-2">UK</div>
<div id="Country-3">UAE</div>
<div id="Country-4">China</div>
<div id="Country-5">India</div>
<div id="Country-6">Japan</div>

Upvotes: 1

Views: 173

Answers (5)

Milimetric
Milimetric

Reputation: 13549

Edited your jsfiddle, added an example of jQuery foreach in a comment. However, you don't need foreach here because jQuery can operate on a collection. I changed your HTML as well, you need to group those divs better:

<div id="Countries">
    <div id="Country-1">USA</div>
    <div id="Country-2">UK</div>
    <div id="Country-3">UAE</div>
    <div id="Country-4">China</div>
    <div id="Country-5">India</div>
    <div id="Country-6">Japan</div>
</div>

$(document).ready(function(){
    hidebutton = $("#hideall");
    hidebutton.click(function(){
        $('#Countries div').hide();
        // $('#Countries div').each(function(index, divElement) { ... });
    });
});

http://jsfiddle.net/nLfNj/3/

Upvotes: 1

Robert Koritnik
Robert Koritnik

Reputation: 105029

There's a CSS3 selector for your needs

As you may know jQuery supports CSS3 selectors whether browser does or doesn't. Hence you can use a more advanced selector that will select all elements with ID starting with Country:

$('div[id^="Country"]').hide();

Upvotes: 4

user578895
user578895

Reputation:

try:

hidebutton.click(function(){
    $('[id^="Country-"]').hide();
});

Note that will also hide any elements that happen to start with "Country-" that you don't want to hide, but assuming you don't have any of those, this will work.

Upvotes: 3

Mike Ruhlin
Mike Ruhlin

Reputation: 3556

give each country a class (i.e. "country"), then do $('.country').hide()

Upvotes: 0

SLaks
SLaks

Reputation: 887453

You can add a class to each of the elements (eg, class="Country"), then write

$('.Country').hide();

Upvotes: 2

Related Questions