Javascript - 切换html5 required =""基于表单选择的属性

时间:2015-03-13 15:56:42

标签: javascript html5

我有一个几乎完整的脚本,但我无法弄清楚最后一块。 Javascript使复选框根据下拉选项显示或消失(这很有效)。但是如果复选框存在(我无法弄清楚的那部分),我试图使复选框“必填”。

我在复选框字段中使用了htm5 required=""属性,但即使选中了第3个选项,表单仍会尝试验证它,这会完全隐藏复选框。

是否可以通过选择下拉菜单或任何其他建议来启用/关闭required=""

<script>    
   function getTerms(select){
        var selectedString = select.options[select.selectedIndex].value;
        if(selectedString == "1" || selectedString == "2")
        {
            document.getElementById("terms_target").style.display = "block";
        }else {
            document.getElementById("terms_target").style.display = "none";
        }
    }
</script>

<form action="process_affiliate.php" method="post" onchange="getTerms(this)" >
<select name="InquiryType" required="">
    <option value="">Please Select Your Inquiry Type</option>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
</select>
<div id="terms_target" style="display:none;">
  <input type="checkbox" name="checked" value="Checked" required="" />I agree to the terms
</div>
<input type="submit" value="Submit">
</form>

1 个答案:

答案 0 :(得分:1)

window.onload=function() {
  var sel = document.getElementsByName("InquiryType")[0];
  sel.onchange=function() {
    var selectedString = this.value,
        show = selectedString == "1" || selectedString == "2",
        terms = document.getElementById("terms_target"),
        checked=document.getElementsByName("checked")[0];
    terms.style.display = show?"block":"none";
    if (show) checked.setAttribute("required","required");
    else checked.removeAttribute("required");
  }
  sel.onchange(); // initialise
}
<form action="process_affiliate.php" method="post">
<select name="InquiryType" required="">
    <option value="">Please Select Your Inquiry Type</option>
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
</select>
<div id="terms_target" style="display:none;">
  <input type="checkbox" name="checked" value="Checked" required="" />I agree to the terms
</div>
<input type="submit" value="Submit">
</form>