0

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.

1
  • 1
    In your edited code you put the logic inside a function, does the function get called? Maybe wrap it in a Document.Ready block or just put in checkTrue() somewhere in the script tags? Commented May 10, 2017 at 17:16

1 Answer 1

1

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

document.querySelector('[name=enabledCheckbox]').checked = true; 
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, but it doesn't seem to be working. I put it in a function and tried to call it onload with an alert for debug purposes, but the function is not being called at all.
the input element doesn't have an onload event, that's why it is not called. Keep the code as you have and invoke the function inside the script, checkTrue();

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.