我在html中有三个复选框。
在Javascript中,我有变量newspaper = "jang,News,Dawn"
;
现在,我想基于报纸的值检查复选框,如果它仅包含jang,则仅jang复选框应被选中,如果它包含jang,News,Dawn,则应选中所有三个复选框。
我编写的代码始终选中了最后两个复选框,这是错误的。
我的代码是:
var newspaper = document.forms[0].newspaper;
var a = "Jang,News";
var news = ["Jang", "Dawn", "News"]
for (i = 0; i < news.length; i++)
{
if (a.indexOf(news[i]))
{
newspaper[i].checked = true;
}
}
<input type="checkbox" name="newspaper[]" value="Jang">Jang<br />
<input type="checkbox" name="newspaper[]" value="Dawn">Dawn<br />
<input type="checkbox" name="newspaper[]" value="News">The News
最佳答案
请更改代码,并替换为:
if (a.indexOf(news[i]))
{newspaper[i].checked = true;
}
通过:
for(j = 0; j < newspaper.length; j++){
if(newspaper[j].value == newspaper[i].value){
if (a.indexOf(news[i])){
newspaper[j].checked = true;
}
}
}