在复选框和输入字段之间切换

时间:2018-03-10 22:39:52

标签: javascript html

我有一个复选框和一个输入字段。如果用户在字段中输入内容,则必须立即取消选中复选框,或者如果用户勾选复选框,则必须禁用该字段。我如何从客户端那样做?

    <label for="postcode">Enter the area postcode you want:</label>
    <input class="form-control" type="text" id="postcode"
           pattern="([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\s?[0-9][A-Za-z]{2})"
           oninvalid="setCustomValidity('Please enter a valid postcode')" oninput="setCustomValidity('')" placeholder="Enter postcode..."><br>
    <label for="nearby">Or</label>
    <div class="checkbox">
        <label><input type="checkbox" id="Nearby" value="">Nearby restaurants</label>
    </div>

1 个答案:

答案 0 :(得分:0)

要达到预期效果,请使用以下选项

  1. 在复选框上添加onchange事件以禁用input-check()函数
  2. 添加oninput事件以取消选中复选框 - tick()函数
  3.     function check(){
          if(document.getElementById('Nearby').checked){
           document.getElementById('postcode').disabled = true
        }else{
          document.getElementById('postcode').disabled = false
        }
        }
        
        function tick(){
          document.getElementById('Nearby').checked = false
        }
      <label for="postcode">Enter the area postcode you want:</label>
        <input class="form-control" type="text" id="postcode"
               pattern="([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))\s?[0-9][A-Za-z]{2})"
               oninvalid="setCustomValidity('Please enter a valid postcode')" oninput="setCustomValidity('');tick()" placeholder="Enter postcode..."><br>
        <label for="nearby">Or</label>
        <div class="checkbox">
            <label><input type="checkbox" id="Nearby" value="" onchange="check()">Nearby restaurants</label>
        </div>

    代码示例 - https://codepen.io/nagasai/pen/oqgrrP