Automatically tick checkbox when clicking on another form input field

Viewed 671

I'm trying to have a checkbox next to a form text-input field. The checkbox can be ticked on/off normally, however when clicking on the text-input field, the checkbox should be automatically ticked as well.

I tried this with putting the text-input inside the label for the checkbox, but it doesn't work. It works fine when I use normal text instead of the input-field:

<input type="checkbox" id="box">
<label for="box">
  <input type="text">
</label>

How can I achieve this with HTML/JS? I'm working in the context of a VueJS plugin.

5 Answers

you can use jquery to achieve this:

HTML:

<input type="checkbox" id="box">
<label for="box"></label>
<input type="text" id="mytextinput">

JQuery:

$('#mytextinput').focus(function(){
$('#box').prop( "checked", true ); // true checks the checkbox false unchecks.
});

Simply add a listener to the text input that checks the box.

const checkbox = document.querySelector('#box');
const input = document.querySelector('input[type="text"]');

input.addEventListener('click', () => {
  checkbox.checked = true;
});
<input type="checkbox" id="box">
<label for="box">
  <input type="text">
</label>

The click action of <input> (focus & start editing) overrides <label>'s, so you'll have to use JS:

document.querySelector('#text').addEventListener('click', ()=>{
  document.querySelector('#box').checked=true
})
<input type="checkbox" id="box">
<input type="text" id="text">

You can do this easily by setting an onclick attribute on text field like:

<input type="checkbox" id="box">
<label for="box">
  <input type="text" onclick="box.checked = true">
</label>

    document.querySelector("#box").addEventListener('click',function(){
        document.querySelector("#checkbox").checked = true;
    });
    <div>
        <input type="checkbox" id="checkbox">
        <input type="text" id="box">
    </div>

Related