0

I am trying to test if checkbox is checked. I have more inputs and they have different names. I managed to select the input but I can't seem to check if it wa selected. If I add to the condition '= true' it is checked once I load the page. If I leave it just .checked it doesn't do anything

  1. Have I selected the input right? Please note I want to select it by name rather than id or class

  2. Why is it that once the page loads my condition for if statement doesn't work?


<input type="checkbox" name="name1">
<input type="checkbox" name="name2">
<input type="checkbox" name="name3">
<input type="checkbox" name="name4">


const firstInput = document.getElementsByName('name1');
if (firstInput[0].checked) {
    console.log('checked');
}
3
  • You are looking for an element with name "1" but you got element with a name "name1". Commented May 31, 2017 at 21:20
  • Oh yes sorry, I meant 'name1'. Once I checked it the console should print checked but it doesn't Commented May 31, 2017 at 21:27
  • Your code works. Where do you perform that check - in a function, in a listener? Commented May 31, 2017 at 21:42

2 Answers 2

1

You are selecting element with name "1" but don`t have element with such name. If you want to select all inputs which name attribute starts with "name":

const firstInput = document.querySelectorAll('[name^=name]')
Sign up to request clarification or add additional context in comments.

Comments

0

You need to add attribute to that input. Attach an onclick listener and invoke

getAttribute setAttribute

to manipulate 'checked' attribute;

<input type="checkbox" onclick="myFunction()" name="name1">
<input type="checkbox" onclick="myFunction()" name="name2">
<input type="checkbox" onclick="myFunction()" name="name3">
<input type="checkbox" onclick="myFunction()" name="name4">


function myFunction() {
  var $element = document.getElementsByName('name1')[0];
  var checked = $element.getAttribute('checked') === 'true';
  $element.setAttribute('checked', !checked);
  console.log($element.getAttribute('checked'));
}

2 Comments

Thank you for the suggestion.
I managed to do it adding the event listener to the checkbox.

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.