Azeem
Azeem

Reputation: 11

how to check checkboxes in javascript

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

Upvotes: 0

Views: 97

Answers (4)

Mudassir
Mudassir

Reputation: 596

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

Upvotes: -1

V2Solutions - MS Team
V2Solutions - MS Team

Reputation: 1127

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/

Upvotes: 0

Prateek
Prateek

Reputation: 4500

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.

Upvotes: 2

Mardoxx
Mardoxx

Reputation: 4482

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/

Upvotes: 0

Related Questions