0

I've got a bunch of checkboxes defined as an array:

<input type="checkbox" value="1" id="courseinfo[]">Content
<input type="checkbox" value="2" id="courseinfo[]">Reputation
<input type="checkbox" value="3" id="courseinfo[]">Duration
<input type="checkbox" value="4" id="courseinfo[]">Career
<input type="checkbox" value="5" id="courseinfo[]">Recommended
<input type="checkbox" value="6" id="courseinfo[]">Interests
<input type="checkbox" value="7" id="courseinfo[]">Other

I am trying to see if the last one (value=7) is checked, I tried:

q2 = document.getElementById("courseinfo[6]").value;

That doesn't seem to work.

How can I access the 7th one in the array and then check if its been checked?

I want to use pure javascript.

3
  • Take out the quotes: q2 = document.getElementById(facilities[6]).value; Commented Jan 31, 2014 at 19:06
  • "facilities[6]" ?? doesn't seems id Commented Jan 31, 2014 at 19:06
  • @GrijeshChauhan sorry you're right I wrote it incorrectly Commented Jan 31, 2014 at 19:08

2 Answers 2

1

You don't have id attribute in your checkbox collection. I think you're meaning name attribute. Use getElementsByName to get elements to NodeList. Then get 6th element's value.

q2 = document.getElementsByName("facilities")[6].value;

Use this to check if checkbox is checked:

if(q2.checked) {
   alert('You have checked the 6th checkbox!');
}
Sign up to request clarification or add additional context in comments.

5 Comments

Right brilliant I missed that part I do have it, how do I acces it to check if its been checked, I have this after: if (q2.checked) {do something}
I think you mean "courseinfo[]" and not "facilities", but yes, this is right.
@abu i added example to check if checkbox is checked.
@josh yes thanks for pointing that out, funny what a cold can do to concentration
@abu I made some modifications to your jsfiddle, can you try now: jsfiddle.net/6GsX3/4
1

document.getElementById is used to get elements from their attribute id="". What you need here is getElementsByTagName

var elems = document.getElementsByTagName('input');
if (elems[elems .length-1].checked) {
    // do stuff
}

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.