Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Checkbox to Checked with JavaScript after page Load

I've got a small challenge in trying to set this checkbox element on my page to checked, after the page loads:

<input type="checkbox" id="1403317">

Challenges:
1. This <input> can only be called by its id since there's no name attribute set.
2. The JS code to do this cannot be placed inside the <head></head> tag - I don't have access to that part of the code in this use case so this must work somewhere in <body></body>.

Here's how I've tried to do this so far (before the closing </body> tag), but with no effect. Is something wrong with my syntax?

<script type="text/javascript">
    window.onload = function() {
    document.getElementById("1403317").checked = true;
    }
</script>
like image 933
dubesor Avatar asked Jul 11 '16 21:07

dubesor


People also ask

How check checkbox is load in JavaScript?

getElementById('takenBefore'). addEventListener('click', event => { if(event. target. checked) { alert("Checkbox checked!"); } });

How call a checkbox is checked in JavaScript?

Onclick function is used to call a JavaScript function to display the Address text when checked. With text box style as style=”display:none” display visibility property as hidden. Here we have created two functions and we will bind these functions to textboxes where if we click the text box would appear.

How do I automatically check a checkbox in HTML?

The checked attribute is a boolean attribute. When present, it specifies that an <input> element should be pre-selected (checked) when the page loads. The checked attribute can be used with <input type="checkbox"> and <input type="radio"> . The checked attribute can also be set after the page load, with a JavaScript.

How do I pre check a checkbox?

After placing a checkbox on the document and selecting the field, go to the properties on the right side under Checkbox Values. Checking the box in the properties will also cause the field to be pre-checked.


1 Answers

This should do what you are looking for. It works correctly in the snippet.

window.onload = onPageLoad();

function onPageLoad() {
  document.getElementById("1403317").checked = true;
}
<input type="checkbox" id="1403317">
like image 196
Will Hamic Avatar answered Nov 15 '22 20:11

Will Hamic