Tester123
Tester123

Reputation: 229

Multiple ID's in jquery/javascript

I have this segment of code

$('#test').click(function(){
 $(this).hide();
 $('#hidethis').show();
});
$('#test2').click(function(){
  $('#hidethis').hide();
  $('#test').show();
})

This Code works fine, I'm however wanting to apply it to more elements. So i want to ideally add more ID's

I have tried this method which hasn't worked.

$('#test,#test3').each.click(function(){
 $(this).hide();
 $('#hidethis').show();
});
$('#test2,#test4').each.click(function(){
  $('#hidethis').hide();
  $('#test').show();
})

Will add a Fiddle if needed

Upvotes: 0

Views: 55

Answers (2)

ozil
ozil

Reputation: 7117

$('.test').click(function () {
    $('.test').each(function(){
        $(this).hide();
    });
    $('#hidethis').show();
});

$('#hidethis').click(function () {
    $(this).hide();
    $('.test').show();
})
.test {
    display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hidethis">HIDE THIS</div>
<div class="test">SHOW ME</div>
<div class="test">SHOW ME1</div>
<div class="test">SHOW ME2</div>
<div class="test">SHOW ME3</div>

Upvotes: 0

YaBCK
YaBCK

Reputation: 3029

All you need to do is the following:

$('#test, #test3').click(function(){
 $(this).hide();
 $('#hidethis').show();
});

$('#test2, #test4').click(function(){
  $('#hidethis').hide();
  $('#test').show();
});

JSFIDDLE EXAMPLE

Upvotes: 1

Related Questions