简体   繁体   English

如何在JavaScript中选中复选框

[英]how to check checkboxes in javascript

I have three checkboxes in html. 我在html中有三个复选框。
In Javascript I have variable newspaper = "jang,News,Dawn" ; 在Javascript中,我有可变newspaper = "jang,News,Dawn" ;

Now I want to check the checkboxes based on newspaper values if it contain only jang then only jang check box should be checked if it contain jang,News,Dawn then all three checkbox should be checked. 现在,我想基于报纸的值检查复选框,如果它仅包含jang,则仅jang复选框应被选中,如果它包含jang,News,Dawn,则应选中所有三个复选框。

The code I have written always checked last two checkboxes which is wrong. 我编写的代码始终选中了最后两个复选框,这是错误的。

My code is: 我的代码是:

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 you want to do it using Javascript only, you have to do some changes in your code : 如果您只想使用Javascript进行操作,则必须对代码进行一些更改:

Change the name of all the checkboxes to "newspaper" (without square brackets) 将所有复选框的名称更改为“报纸”(不带方括号)

<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

Check indexOf return value is not equal to -1 : 检查indexOf返回值不等于-1:

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

Here is the working demo . 这是工作示例

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;
          }
}

Yeah, I would review your code, and the names of your elements. 是的,我将检查您的代码以及元素的名称。 But here, this works. 但是在这里,这可行。

http://jsfiddle.net/3qeeox0a/ http://jsfiddle.net/3qeeox0a/

Try this- 尝试这个-

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;
        }
    }

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

Please change the code, and replace this: 请更改代码,并替换为:

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

by: 通过:

for(j = 0; j < newspaper.length; j++){
   if(newspaper[j].value == newspaper[i].value){
      if (a.indexOf(news[i])){
         newspaper[j].checked = true;
      }
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM