【问题标题】:Automatically tick checkbox when clicking on another form input field单击另一个表单输入字段时自动勾选复选框
【发布时间】:2020-09-17 04:56:49
【问题描述】:

我正在尝试在表单文本输入字段旁边设置一个复选框。复选框可以正常勾选/关闭,但是当点击文本输入字段时,复选框也应该自动勾选。

我尝试将文本输入放在复选框的标签内,但它不起作用。当我使用普通文本而不是输入字段时它工作正常:

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

如何使用 HTML/JS 实现这一点?我在 VueJS 插件的上下文中工作。

【问题讨论】:

标签: javascript html forms input checkbox


【解决方案1】:

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

【讨论】:

  • @FZs 兄弟我还没有看到你的解决方案。实际上,当我开始时,这里没有一个答案
  • 没问题...刚刚提到
【解决方案2】:

&lt;input&gt;(聚焦和开始编辑)的点击操作会覆盖&lt;label&gt;,所以你必须使用 JS:

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

【讨论】:

    【解决方案3】:

    您可以通过在文本字段上设置onclick 属性来轻松做到这一点,例如:

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

    【讨论】:

      【解决方案4】:

      只需将侦听器添加到选中该框的文本输入即可。

      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>

      【讨论】:

        【解决方案5】:

        你可以使用 jquery 来实现:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-10-03
          • 2018-12-25
          • 2021-08-28
          相关资源
          最近更新 更多