js code works for one variable(?), how to make it work for many?

Posted by jerry87 on Stack Overflow See other posts from Stack Overflow or by jerry87
Published on 2012-03-20T16:54:22Z Indexed on 2012/03/20 17:29 UTC
Read the original article Hit count: 138

Filed under:
|
|
|

I have working code of js, it shows different div for selected option.

<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>    
<script type="text/javascript">
$(document).ready(function(){
$('#box1').hide();
$('#box2').hide();
$('#box3').hide();
$("#thechoices").change(function(){
$("#" + this.value).show().siblings().hide();
});    
$("#thechoices").change();
});
</script>
</head>
<body>

<select id="thechoices">
<option value="box1">Box 1</option>
<option value="box2">Box 2</option>
<option value="box3">Box 3</option>
</select>

<!-- the DIVs -->
<div id="boxes">
<div id="box1"><p>Box 1 stuff...</p></div>
<div id="box2"><p>Box 2 stuff...</p></div>
<div id="box3"><p>Box 3 stuff...</p></div>
</div>    
</body>
</html>

Please, I have no js experience, so I don't know how to make it work several times on one page for many "thechoices". Something like copy paste but more suitable than this:

    <script type="text/javascript">
$(document).ready(function(){
$('#box1').hide();
$('#box2').hide();
$('#box3').hide();

$('#box4').hide();
$('#box5').hide();
$('#box6').hide();
$("#thechoices").change(function(){
$("#" + this.value).show().siblings().hide();
});
$("#thechoices2").change(function(){
$("#" + this.value).show().siblings().hide();
});

$("#thechoices").change();
});
$("#thechoices2").change();
});
</script>
</head>
<body>

<select id="thechoices">
<option value="box1">Box 1</option>
<option value="box2">Box 2</option>
<option value="box3">Box 3</option>
</select>

<!-- the DIVs -->
<div id="boxes">
<div id="box1"><p>Box 1 stuff...</p></div>
<div id="box2"><p>Box 2 stuff...</p></div>
<div id="box3"><p>Box 3 stuff...</p></div>
</div>

<select id="thechoices2">
<option value="box4">1</option>
<option value="box5">2</option>
<option value="box6">3</option>
</select>

<!-- the DIVs -->
<div id="boxes">
<div id="box4"><p>1 stuff...</p></div>
<div id="box5"><p>2 stuff...</p></div>
<div id="box6"><p>3 stuff...</p></div>
</div>

I know you can help me, it seems to be simple but I can't handle with this. How can I change my second code to work in the same way but not only for two selectors. I need it for many. Don't want to copy paste the same section like in my second code.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery