我的页面上有以下代码,几乎没有复选框.

<form>
    <input type="checkbox" id="CatFood" /><b>Cat Food</b><br /><br />
    <input type="checkbox"  id="Food1" name="test222" onclick="reported(this)"  />Delicious Food<br />
    <input type="checkbox" id="Food2" name="test222" onclick="reported(this)" />Healthy Food<br /><br /><br />
  
 
    <button type="submit">Submit</button>

</form>
    

一旦用户点击cat 粮,我希望终端用户点击"美味食品"复选框或"健康食品"复选框,但不能同时点击两者.只需要其中一个复选框.为了实现这一点,我try 编写以下代码:

 <script>
           $(function(){
            $('#CatFood').on('click', function () {
                    if($(this).is(':checked')){

                    $('.Food1').attr('required', 'required') || $('.Food2').attr('required', 'required');
                    }else{

                    $('.Food1').removeAttr('required');
                    }
         
                });
            }); 
   
  

</script>

单击提交按钮时没有任何react .我可以使复选框单选按钮,但在我的例子中,我希望它是复选框.以下是屏幕截图:

enter image description here

以下是已报告的代码:

报告的函数(复选框){

        var checkboxes = document.getElementsByName('test222')
        checkboxes.forEach((item) => {
            if (item !== checkbox) item.checked = false
        })

    }

I already looked at the following stack overflow link, but that did not help:

GetElement

GetElement2

推荐答案

正如其他一些人指出的,使用单选按钮可能是更好的 Select ,但如果你真的想使用复选框,下面的代码可以帮助你实现你的目标.

<form>
  <input type="checkbox" id="catFood" onclick="makeCatFoodsRequired(this)" />
  <b>Cat Food</b><br /><br />
  <input type="checkbox" id="food1" class="catFoods" name="food" onclick="clearOtherCatFoods(this)" />
  Delicious Food <br />
  <input type="checkbox" id="food2" class="catFoods" name="food" onclick="clearOtherCatFoods(this)" />
  Healthy Food<br />
  <br /><br />
  <button type="submit">Submit</button>
</form>

<script>
  function makeCatFoodsRequired(checkbox) {
    const catFoods = document.querySelectorAll('.catFoods');

    if (checkbox.checked) {
      catFoods.forEach(food => food.required = true);
    } else {
      catFoods.forEach(food => food.required = false);
    }
  }

  function clearOtherCatFoods(checkbox) {
    const catFoods = document.querySelectorAll('.catFoods');

    catFoods.forEach(food => {
      if (food !== checkbox) {
        food.checked = false;
        food.required = false;
      } else {
        food.required = true;
      }
    });
  }
</script>

Javascript相关问答推荐

如何提取Cypress中文本

在贝塞尔曲线的直线上找不到交叉点:(使用@Pomax的bezier.js)

有条件的悲剧

使用复选框在d3.js多折线图中添加或删除线条

点击按钮一次有文本出现和褪色,而不是点击两次?(html,CSS,JavaScript)

为什么按钮会随浮动属性一起移动?

如何根据当前打开的BottomTab Screeb动态加载React组件?

获取Uint8ClampedArray中像素数组的宽度/高度

如何在bslib nav_insert之后更改导航标签的CSS类和样式?

并不是所有的iframe都被更换

rxjs插入延迟数据

如何将数组用作复合函数参数?

JavaScript是否有多个`unfined`?

OpenAI转录API错误请求

传递方法VS泛型对象VS事件特定对象

当我点击一个按钮后按回车键时,如何阻止它再次被点击

Socket.IO在刷新页面时执行函数两次

在每次重新加载页面时更改指针光标

将Windows XP转换为原始数据以在html前端中显示

如何在不将整个文件加载到内存的情况下,在Node.js中实现Unix粘贴命令?