0

I want to add checked option to checkbox if it has an id or value of 2 at runtime using javascript. I tried with following code, but I am unable to check the checkbox. Any ideas?

<div>
        <h4>Filter by Area</h4>             
            <ul id="arealist">
    <li><input type ="checkbox"  id="1" value="1" /> All</li>
    <li><input type ="checkbox"   id="2" value="2" /> some</li>
    <li><input type ="checkbox"   id="3" value="3" /> heavy</li>
    <li><input type ="checkbox"   id="4" value="4" /> more</li>
    <li><input type ="checkbox"   id="5" value="5" /> none</li>

                                            </ul>   </div>
<script type="text/javascript" src="<?=base_url()?>js/jquery-1.6.4.min.js"></script>    
<script type="text/javascript">
$(document).ready(function(){  
var areaname=2; //this value i am getting at run time.
$("#areaname").prop("checked",true);
});
</script>
Chris Barlow
  • 3,274
  • 4
  • 31
  • 52
srinu
  • 259
  • 3
  • 7
  • 14

3 Answers3

5

You need to concatenate your string.

$("#" + areaname).prop("checked", true);

Live example

Also, your ID names are invalid. Think of them as variables. Use names that don't start with numbers, don't have spaces, etc.

Community
  • 1
  • 1
Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
0

Try

$("#" + areaname).attr("checked", true);

Instead of

$("#areaname").prop("checked",true);
bobek
  • 8,003
  • 8
  • 39
  • 75
0

Your ID attribute cannot be just an integer, it must begin with a letter. If you name them something like area1, area2, area3 etc... and update your code it should work fine. Here's a JSFiddle with an updated version working fine.

musicinmyhead
  • 1,466
  • 9
  • 11
  • Hi srinu thanks for the accept :) Please go ahead and give @Xeon06 a vote up as well for posting an equally useful answer :) – musicinmyhead Mar 01 '12 at 15:08