wortle
wortle

Reputation: 41

Show hide image by generated id

I have this code that generates a group ID with javascript. It's shown here: http://jsfiddle.net/LwtvK/5/. Now instead of it writing the text "Group id : X", I want it to control an image that gets shown. There are 7 group id's and 7 images

    <div data-role="content" id="pictures"> 
        <img src="images/image1.jpg" alt="image" id="pict1">
        <img src="images/image2.jpg" alt="image" id="pict2">    
        <img src="images/image3.jpg" alt="image" id="pict3">    
        <img src="images/image4.jpg" alt="image" id="pict4">    
        <img src="images/image5.jpg" alt="image" id="pict5">    
        <img src="images/image6.jpg" alt="image" id="pict6">    
        <img src="images/image7.jpg" alt="image" id="pict7">    
    </div>

Now when the group id is 5, I want the 'Continue' button to hide images 1, 2, 3, 4, 6 and 7 and show image 5. I was thinking of doing something like

    function show_img(id)
    {
        if(id=='1')
        {
           $("#pict1").hide();
           $("#pict2").show();
        }
        else if(id=='2')
        {
            $("#pict2").show();
            $("#pict1").hide();
        }
    return false;
     } 

But that would result in a lot of retyping and I'm not really sure how to get it to work. So, does anyone know how I can get the generated group ID to show the right image when the button is clicked?

Upvotes: 1

Views: 1277

Answers (4)

WTK
WTK

Reputation: 16971

You could hide all (using some general selector) and then show just the one you need. E.g.

function show_img(id) {
    // hide every image that is immediate child of node with "pictures" id
    $('#pictures > img').hide();
    $('#pict'+id).show();
}

Upvotes: 6

David Thomas
David Thomas

Reputation: 253318

I'd suggest (though untested):

 function show_img(id) {
    $('#img' + id).show().siblings().hide();
 }

Upvotes: 2

Richard Dalton
Richard Dalton

Reputation: 35793

The following code will hide all images with an id starting img then show the one with the id passed in:

function show_img(id)
{
    $('img[id^="img"]').hide();
    $('#img' + id).show();
} 

http://jsfiddle.net/3U96T/1/

Upvotes: 2

Lix
Lix

Reputation: 47976

Something like this might be useful -

function show_img(id)
{
  // hide all other images (possibly only within a certain parent element)
  $("#parent_selector > img").hide();

  // display only specified image by id
  $("#img"+id).show();
  return false;
}

Upvotes: 2

Related Questions