简体   繁体   中英

Check if is it checked on - <input type='checkbox'>

I try to do as describe in - check if checkbox is checked javascript

And this is my code -

var input = document.createElement("input");
input.name = "test";
input.type = "checkbox";
input.checked = true ;
var currentInput = document.getElementsByName("test");
if (currentInput.checked) {
    console.log("true");
}

but after run it nothing logs to the console although the input.checked = true assignment.

Why doesn't it logs true ?

Edit:

According to what @adeneo and @mori57 said , now the follow -

var input = document.createElement("input");
input.name = "test";
input.type = "checkbox";
input.checked = true;
var body = document.getElementsByTagName('body')[0];
body.appendChild(input);
var currentInput = document.getElementsByName("test")[0];
if (currentInput.checked) {
    console.log("true");
}

logs true

Whenever you see getElements.. , as in plural, and not getElement... it means you're getting a nodeList not a single element, even if there is only one element in that nodeList

You can access nodeLists like arrays, so nodeList[0] is the first element in the list

var currentInput = document.getElementsByName("test")[0];

Of course, you already have a reference to the element, so you don't have to get it again

var input = document.createElement("input");
input.name = "test";
input.type = "checkbox";
input.checked = true ;

if (input.checked) { // this will always be true, so it makes no sense
    console.log("true");
}

and as pointed out in the comment by @mori57, you never add the element to the DOM, so you can't get it with document.getEleme.... methods when it doesn't exist.

I'm guessing what you really want is an event handler

var input = document.createElement("input");
input.name = "test";
input.type = "checkbox";
input.checked = true ;

input.addEventListener('change', function() {
    console.log( this.checked );
}, false);

The problem is that document.getElementsByName("test") returns an array, so you would need to use a certain element of the array:

If it is the only one, you can just select the first one:

document.getElementsByName("test")[0]

So, your new code would be:

var input = document.createElement("input");
input.name = "test";
input.type = "checkbox";
input.checked = true ;
var currentInput = document.getElementsByName("test")[0];
if (currentInput.checked) {
    console.log("true");
}

As pointed out by mori57 's comment ,

You never actually create the element, causing it to not be possible to be discovered. You would need to use something such as:

document.body.appendChild(input);

Before declaring currentInput in order for it to be able to be found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM