如何在运行时检查复选框

sri*_*inu 0 javascript jquery

如果在运行时使用javascript的id或值为2,我想将复选选项添加到复选框.我尝试使用以下代码,但我无法选中复选框.有任何想法吗?

<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>
Run Code Online (Sandbox Code Playgroud)

Ale*_*pin 5

你需要连接你的字符串.

$("#" + areaname).prop("checked", true);
Run Code Online (Sandbox Code Playgroud)

实例

此外,您的ID名称无效.将它们视为变量.使用不以数字开头,没有空格等的名称.