问题根据复选框状态更改输入字段属性

时间:2018-11-08 12:48:01

标签: javascript html

我正在使用一个复选框来显示一些包装在div中的输入字段。单击复选框时,div正确显示,而未单击时,div隐藏正常。默认情况下,div中的输入字段不是必需的(可选)。

我想创建一个Js逻辑,如果用户单击该复选框,则字段应将属性更改为强制性/必需。

是Js学习者,请帮忙吗?

复选框代码以隐藏或显示下面的div

<label class="spouse-me">
    <h1 class="pumba">Spouse</h1>
    <input type="hidden" class="spouse" value="0" />
    <input type="checkbox" id="spouse" value="1" class="spouse" onclick="checkMark()">
</label>

该复选框正在显示或隐藏该

//Parent div
<div class="spouseDetail" id="spouseDetail" style="display:none;">
  //Child div
  <div class="form-line registar love {{ $errors->has('spousename') ? ' has-error' : '' }}" style="margin-left: 0px;">
    <input type="text-area" class="form-input" name="spousename" id="spouseName" value="{{ old('spousename') }}">
    <label>Spouse Name *</label>
    <div class="error-label">Field is required!</div>
    <div class="check-label"></div>
    @if ($errors->has('spousename'))
        <span class="help-block">
            <strong>{{ $errors->first('spousename') }}</strong>
        </span>
    @endif
</div>

<div class="form-line registar love {{ $errors->has('spousedob') ? ' has-error' : '' }}">
  <input type="date" class="form-input" name="spousedob" id="spouseDob" value="{{ old('spousedob') }}">
  <label>Date of Birth *</label>
  <div class="error-label">Field is required!</div>
  <div class="check-label"></div>
  @if ($errors->has('spousedob'))
        <span class="help-block">
        <strong>{{ $errors->first('spousedob') }}</strong>
        </span>
  @endif
</div>

</div>

JavaScript函数

  function checkMark() {
      var checkBox = document.getElementById("spouse");
      var text = document.getElementById("spouseDetail");

      // If the checkbox is checked, display the output text
      if (checkBox.checked == true){
        text.style.display = "block";
      } else {
        text.style.display = "none";
      }
    }

1 个答案:

答案 0 :(得分:0)

也许您可以尝试这样的事情。

  if (checkBox.checked == true){
    text.style.display = "block";
    var inputElm = document.getElementsByTagName(INPUT);
    for(var i=0; i<inputElm.length; i++) {
        inputElm[i].required = true;
    }
  } else {
    text.style.display = "none";
  }