Search code examples
javascriptasp.net-mvccheckboxnested-checkboxes

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

Solution

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