Wrostran Wrostran - 6 months ago 16
CSS Question

Javascript with dropdown to show div

Can someone look at my code, something is not working, this is my first java based on some tutorials but for some reason is not working, i put it in a php file and uploaded to my server then i doest work anymore. i checked it in JSFddle and it was working.

<head>
<style type="text/css">
.div1 {color: red; display:none}
.div2 {color: blue; display:none}
.div3 {color: red; display:none}
.div4 {color: blue; display:none}
.div5 {color: red; display:none}
</style>

<script type"text/javascript" src="//http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type"text/javascript">
$("#cities").change(function(){
var value = this.value;
if (value == "1"){
$(".div1").show();
$(".div2").hide();
$(".div3").hide();
$(".div4").hide();
$(".div5").hide();
}else if (value == "2"){
$(".div1").hide();
$(".div2").show();
$(".div3").hide();
$(".div4").hide();
$(".div5").hide();
}else if (value == "3"){
$(".div1").hide();
$(".div2").hide();
$(".div3").show();
$(".div4").hide();
$(".div5").hide();
}
});
</script>
<title></title>
</head>
<body>
<select class="cities" id="cities" name="project_procurement_management_plan[items_attributes][0][category_id]">
<option value="">select one</option>
<option value="1">this is 1</option>
<option value="2">this is 2</option>
<option value="3">this is 3</option>
</select>
<hr>
<div class="div1">1</div>
<div class="div2">2</div>
<div class="div3">3</div>
</body>
</html>


Thanks guys

Answer

Your script type tag has problem, change

<script type"text/javascript">

to

<script type="text/javascript">

and place your entire .change() code inside DOM ready handler, like

$(document).ready(function() {
   $("#cities").change(function(){
      //rest of your code
   });
});

and remove // at start, from jQuery url as well