显示基于select的复选框

时间:2015-10-09 08:22:09

标签: javascript jquery checkbox drop-down-menu

我是javascript / jquery的新手,并且根据下拉列表的值有必要使复选框成为必填项。我想复选框是隐藏的,如果" Guest"已选中,如果" A / C"选中,则显示复选框并强制使用被选中。有人可以帮忙吗?

<script type="text/javascript">
function ShowHideDiv2() {
    var Payment1 = document.getElementById("Payment1");
    var BCO = document.getElementById("BCO");
    BCO.style.display = Payment1.value == "A/C" ? "block" : "none";
}
</script>

<select name="Payment 1" id="Payment1" editable="true" onchange = "ShowHideDiv2()">
<option value="null" selected>Select... </option>
<option value="A/C">A/C</option>
<option value="Guest">Guest</option>
</select>

<div id="BCO" style="display: none">
<input name="BCO Approved" type="checkbox" value="Yes">
I will pay by A/C.
</div>

4 个答案:

答案 0 :(得分:0)

$('#Payment1').change(function(){
var selected = $('option:selected',this).val(); 
if(selected == 'A/C'){
    $('#BCO').show();
}else{
$('#BCO').hide();
}

})

DEMO

在选择get的更改事件时,选择的选项会将其与Guest进行比较,如果相同则显示div

答案 1 :(得分:0)

如果你使用jQuery

,这将是和平的蛋糕
$(document).ready(function(){
$("#Payment1").change(function(){
    $this = $(this);
    if($this.val() === "A/C"){
        $("#chBox").css("display","block");
    }else{
        $("#chBox").css("display","none");
    }
  });
});

jsFiddle demo

答案 2 :(得分:0)

使用纯JavaScript代码,如果您将html元素包装在表单中,则可以轻松实现结果:

&#13;
&#13;
 
function ShowHideDiv2() {
    var Payment1 = document.getElementById("Payment1");
    var BCO = document.getElementById("BCO");
    BCO.style.display = Payment1.value == "A/C" ? "block" : "none";
    document.getElementById("myId").required = (BCO.style.display == "block");
      
}
 
&#13;
 
<form>
<select name="Payment 1" id="Payment1" editable="true" onchange = "ShowHideDiv2()">
<option value="null" selected>Select... </option>
<option value="A/C">A/C</option>
<option value="Guest">Guest</option>
</select>

  
<div id="BCO" style="display: none">
<input name="BCO Approved" type="checkbox" value="Yes" id="myId">
I will pay by A/C.
</div>
  <input type="submit" value="submit">
  <form>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

我想你需要做这样的事情:

var Payment1 = document.querySelector("#Payment1");
var BCO = document.querySelector("#BCO");

function ShowHideDiv2() {
  BCO.style.display = Payment1.value == "A/C" ? "block" : "none";
}

document.querySelector('button').addEventListener('click', function() {
  var child = BCO.querySelector('input[type="checkbox"]');
  if (BCO.style.display === "block" && !child.checked) {
    alert('Payment by A/C is required.');
  }

});
<select name="Payment 1" id="Payment1" editable="true" onchange="ShowHideDiv2()">
  <option value="null" selected>Select...</option>
  <option value="A/C">A/C</option>
  <option value="Guest">Guest</option>
</select>

<div id="BCO" style="display: none">
  <input name="BCO Approved" type="checkbox" value="Yes">I will pay by A/C.
</div>

<p>
  <button>submit</button>
</p>