0

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
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Azeem
  • 11
  • 1
  • 7

4 Answers4

2

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.

Prateek
  • 4,220
  • 1
  • 17
  • 22
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;
          }
}

Yeah, I would review your code, and the names of your elements. But here, this works.

http://jsfiddle.net/3qeeox0a/

Mardoxx
  • 4,372
  • 7
  • 41
  • 67
0

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/

-1

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;
      }
   }
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Mudassir
  • 578
  • 4
  • 6