2

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.

Klausette
  • 362
  • 1
  • 3
  • 14
  • Does this answer your question? [How to check a checkbox on focus of Input text in table](https://stackoverflow.com/questions/45358888/how-to-check-a-checkbox-on-focus-of-input-text-in-table) – rxdue May 29 '20 at 15:11
  • Does this answer your question? [How to create a checkbox with a clickable label?](https://stackoverflow.com/questions/6293588/how-to-create-a-checkbox-with-a-clickable-label) – 0stone0 May 29 '20 at 15:11

5 Answers5

2

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.
});
2

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>
terrymorse
  • 6,771
  • 1
  • 21
  • 27
2

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">
FZs
  • 16,581
  • 13
  • 41
  • 50
1

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>
palaѕн
  • 72,112
  • 17
  • 116
  • 136
1

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