Your syntax wouldn’t work because you can’t assign to the result of a function.
The spellcheck
attribute has the somewhat weird requirement that its values should match exactly "true"
or "false"
.
This means it’s an enumerated attribute, but not a boolean attribute.
But the values are boolean literals, as strings.
If you encounter any attribute that behaves this way, this is how you can toggle it:
textArea.setAttribute("spellcheck", !JSON.parse(textArea.getAttribute("spellcheck")));
JSON.parse
accepts (among other things) a boolean literal as a string, i.e. "true"
or "false"
, and turns it into an actual boolean.
The string value is retrieved with getAttribute
.
The logical NOT (!
) inverts the parsed boolean.
Then, setAttribute
sets the result (no need to convert the boolean back into a string: attribute values can only be strings, so setAttribute
performs this conversion for you).
If you had a true boolean attribute such as contenteditable
, then this is much easier done with toggleAttribute
.
Your event listener relies on the click
event.
But toggling a checkbox can be achieved many other ways (e.g. keyboard navigation, touch, etc.).
Use the change
event instead.
document.getElementById("sampleCheckbox").addEventListener("change", () => {
const textArea = document.getElementById("sampleTextarea");
textArea.setAttribute("spellcheck", !JSON.parse(textArea.getAttribute("spellcheck")));
});
<label>Enable / Disable Spellcheck: <input id="sampleCheckbox" type="checkbox" checked></label>
<textarea id="sampleTextarea" spellcheck="true" rows="5" cols="50">sadadadadadsasamkdajdakmkmxzcm</textarea>