vendredi 14 août 2020

Problem to set checkbox checked with javascript

I come to you because I have a problem setting the checked property with javascript. I create this checkbox with createlement and put it inside the li tag.

var item = response.Result[i];
var checkboxId = "chk_modulePermission_" + item.Position;
var li = document.createElement("LI");
li.classList.add("list-group-item");
li.classList.add("form-check");

var checkbox = document.createElement("input");
checkbox.setAttribute("type", "checkbox");
checkbox.setAttribute("id", checkboxId);
checkbox.setAttribute("name", "modulePermissions");
checkbox.value = item.Position;
checkbox.classList.add("permission-item");

var label = document.createElement("label");
label.setAttribute("for", checboxId);
label.classList.add("form-check-label");
label.innerText = " "+item.ESTextDisplay;

li.appendChild(checkbox);
li.appendChild(label);
accessGroupList.appendChild(li);

Later I want to set it as checked and I use the following code, but it returns null when I want to obtain it with getElementById, the Id attributes match in both functions

          moduleIdSelect.dispatchEvent(new Event('change'));
            profiles.getProfiles(fieldId).then(function (response) {
                if (response === null) return;
                for (var i in response.Result) {
                    var permission = response.Result[i]==="true";
                    //console.log("permission: " + permission);
                    if (permission === true) {
                        var checkboxId = "chk_modulePermission_" + i;
                        console.log("checkboxId: " + checkboxId);
                        var element = document.getElementById(checkboxId);
                        element.setAttribute("checked", true);
                    }
                    
                }
            });

I get the following error in the line "element.setAttribute("checked", true);":

Uncaught (in promise) TypeError: Cannot read property 'setAttribute' of null at ....

As I see it is correct, but I do not know what may be happening.

Could you help me? Thank you very much.




Aucun commentaire:

Enregistrer un commentaire