how to check checkboxes in javascript

100 views Asked by At

I have three checkboxes in html.
In Javascript I have variable 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.

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
4

There are 4 answers

0
Mudassir On BEST ANSWER

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;
      }
   }
}
0
Mardoxx On
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/

0
Prateek On

If you want to do it using Javascript only, you have to do some changes in your code :

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 :

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

Here is the working demo.

0
V2Solutions - MS Team On

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/