0

我在 html 中有三个复选框。
在Javascript中我有变量newspaper = "jang,News,Dawn"

现在我想根据报纸值检查复选框,如果它只包含 jang,那么如果它包含 jang、News、Dawn,那么只应该检查 jang 复选框,然后应该检查所有三个复选框。

我编写的代码总是检查最后两个错误的复选框。

我的代码是:

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
4

4 回答 4

2

如果你只想使用 Javascript 来做,你必须在你的代码中做一些改变:

将所有复选框的名称更改为“报纸”(不带方括号)

<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

检查indexOf返回值不等于 -1 :

if (a.indexOf(news[i]) != -1) {
    newspaper[i].checked = true;
}

这是工作演示

于 2014-09-16T11:57:33.447 回答
0
var newspaper = document.forms[0]["newspaper[]"];
var a = "Jang,News";
for (i = 0; i < newspaper.length; i++)
{
       if(a.indexOf(newspaper[i].value) > -1){
             newspaper[i].checked = true;
          }
}

是的,我会查看您的代码和元素的名称。但是在这里,这行得通。

http://jsfiddle.net/3qeeox0a/

于 2014-09-16T11:54:22.753 回答
0

尝试这个-

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]) != 1)
        {
            newspaper[i].checked = true;
        }
    }

小提琴:- http://jsfiddle.net/um0y5wrp/9/

于 2014-09-16T12:58:14.743 回答
-1

请更改代码,并替换此代码:

   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;
      }
   }
}
于 2014-09-16T11:48:56.623 回答