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
1
  • 1
    also a.indexOf(news[i]) >= 0) to allow match on the first char Commented Sep 16, 2014 at 11:44

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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/

Comments

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/

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.