0

How can I change an html checkbox dynamically using JavaScript?

I need a checkbox to be updated (ie ticked) after a key press.

<label class="switch">
<input type="checkbox" id = "record">
<div class="slider round">
</div>

Update: this is what I was looking for:

document.getElementById('record').checked = true;
  • Do you mean changing its appearance when checked? – IiroP Jun 20 '17 at 15:43
  • I mean being able to set it to "checked" remotely, so the appearance changes when I press a key. – Adam Parkinson Jun 20 '17 at 15:44
  • You would need to write some Javascript to do it. What part do you not know how to do, reacting to a keypress or changing the checkbox status? Have you followed the instructions/documentation/tutorials you find when you google those tasks? – JJJ Jun 20 '17 at 15:49
  • 2
    Possible duplicate of [Check/Uncheck checkbox with javascript?](https://stackoverflow.com/questions/8206565/check-uncheck-checkbox-with-javascript) – Alexander Jun 20 '17 at 15:55

1 Answers1

0

You can use ELEMENT.checked = true or false to set its check status.

document.addEventListener('keydown', function(e){
    // assuming desired key is "enter". You can change it to whatever key you prefer.
    if (e.which == 13){
        document.getElementById('record').checked = true;
    }
});
yqlim
  • 6,898
  • 3
  • 19
  • 43