Hello people,

I want that when I mouse over a checkbox, that it is checked.

I have now the following code:

<script language=javascript>
function checkit(myform, name)
{
var xx = document.myform.name;
xx.checked = true;
}
</script>

<form name=myform27>
<input type=checkbox name=mycheck onMouseOver="checkit(myform27,mycheck)" value="1"> Checking
</form>

But this does not work, it says "document.myform is undefined".

How to solve this, and what are i am doing wrong?

Dani AI

Generated

the error comes from mixing up variables and DOM lookups. In your handler you pass references, but then you read document.myform.name using literal property names. The browser only exposes a forms collection at document.forms, and each form exposes its controls via form.elements[...]. So target the checkbox as document.forms["myform27"].elements["mycheck"] (or, better, give it an id and use getElementById). See HTMLFormElement.elements.

If you want hover to always check (not toggle) and keep markup clean, bind listeners once and set the property directly. This follows what hinted (use the form/element APIs) without relying on inline JS, and avoids the toggle behavior in ’s snippet.

<form id="myform27">
  <label>
    <input type="checkbox" id="mycheck" value="1"> Checking
  </label>
</form>

<script>
const cb = document.getElementById("mycheck");

// Always check on hover
cb.addEventListener("mouseenter", () => { cb.checked = true; });

// Optional: uncheck when leaving
// cb.addEventListener("mouseleave", () => { cb.checked = false; });
</script>

Notes:

  • checked is the live state you want to set/read; the HTML checked attribute only sets the default. Docs: HTMLInputElement.checked.
  • mouseenter is usually better than mouseover here because it does not fire when moving over child nodes. Docs: Element mouseenter event.
  • UX/accessibility: hover-to-check is surprising and does not work on touch or with the keyboard. Consider keeping click to toggle and use a <label> to enlarge the hit area instead of changing state on hover. Docs: label element.

Recommended Answers

All 3 Replies

How about this:

<script type="text/javascript">
function checkit(formName, checkBox) {
var xx = document.formName.elements.checkBox;
xx.checked = 1;
}
</script>

<form name="myform">
  <input type="checkbox" name="mycheck" onMouseOver="checkit('myform','mycheck')" value="1"> Checking</input>
</form>

Or you can just simplify things by doing this:

<form name="myform27" action="#" onsubmit="return false;">
<label for="chk1">
<input type="checkbox" name"myCheck" id="chk1" onmouseover="if (!this.checked) { this.checked = true; } else { this.checked = false; }" />Checkbox</label>
</form>
commented: Solved my problem correctly +1

Thanks guys, you two solved my whole problem!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.