简体   繁体   中英

Javascript Checkbox Ticked on Load Error

I have a .cshtml page that I'm going to set up with several checkboxes.

The checkboxes should be checked/unchecked depending on the values of several variables passed into the view using the TempData.

I've set up the code as follows:

<script>

    @if (TempData["enabled"] == "True") {
       var eCheckBox = document.getElementById(eCheck);
       eCheckBox.checked = true;

    }

</script>

<h2>Update @TempData["fullName"]</h2>

<input type="checkbox" name="enabledCheckbox" value="Enabled" id="eCheck"/>Enabled<br/>

But the line

eCheckBox.checked = true; 

produces the error 'identifier expected;checked is a keyword'. Is there something obvious I'm missing? Making a checkbox ticked on load seems like it should be simple to do.

EDIT: I tried to correct the code as follows:

<input type="checkbox" name="enabledCheckbox" value="Enabled" id="eCheck" onload="checkTrue()"/>Enabled<br/>

<script type="text/javascript">

    function checkTrue() {
        alert("Here!");


        if (TempData["enabled"] == "True") {
            document.querySelector('[name=enabledCheckbox]').checked = true;
        }
    }

</script>

It doesn't look as though the code is hitting the function at all, as no alert fires.

You miss to retrieve your HTML element correctly through JS. Just use this:

document.querySelector('[name=enabledCheckbox]').checked = true; 

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