在Jquery中切换detach()选择器

时间:2016-08-31 03:19:42

标签: javascript jquery html css

我有三个单选按钮,我想在input:radio[].val !== 'samplename'时分离div。

这些是我的收音机按钮

<div class="form-group">
    <input checked="check" type="radio" value="Invididual" name="type_of_membership" id="radio-indi"> <label class="default-link" for="radio-indi">Individual</label>&nbsp;&nbsp;&nbsp;&nbsp;
    <input type="radio" value="Institution" name="type_of_membership" id="radio-ins"> <label class="default-link" for="radio-ins">Institution</label>&nbsp;&nbsp;&nbsp;&nbsp;
    <input type="radio" value="Corporation" name="type_of_membership" id="radio-corp"> <label class="default-link" for="radio-corp">Corporation</label>
</div>

这是我当前的JS SCRIPT

var comapany_input = $("#company-div");

$("input[type='radio']").click(function() {

    if (!$('input:radio').is(':checked').val() == "Corporation") {
        comapany_input.detach();


    } else {

        comapany_input.appendTo("body");
        comapany_input = null;
    }
});

1 个答案:

答案 0 :(得分:0)

您需要使用

if($('input:radio:checked').val() != "Corporation") {

获取已选中复选框的值。

if(!$('input:radio').is(':checked').val() == "Corporation") {会抛出错误,因为is方法会返回boolean没有val方法的值。

&#13;
&#13;
var comapany_input = $("#company-div");
$("input[type='radio']").change(function() {
  if (this.checked && this.value == 'Corporation') {
    comapany_input.appendTo('body');
  } else {
    comapany_input.detach();
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <input checked="check" type="radio" value="Invididual" name="type_of_membership" id="radio-indi">
  <label class="default-link" for="radio-indi">Individual</label>&nbsp;&nbsp;&nbsp;&nbsp;
  <input type="radio" value="Institution" name="type_of_membership" id="radio-ins">
  <label class="default-link" for="radio-ins">Institution</label>&nbsp;&nbsp;&nbsp;&nbsp;
  <input type="radio" value="Corporation" name="type_of_membership" id="radio-corp">
  <label class="default-link" for="radio-corp">Corporation</label>
</div>
<div id="company-div">company-div</div>
&#13;
&#13;
&#13;

您可以隐藏/显示元素,而不是

&#13;
&#13;
var comapany_input = $("#company-div");
$("input[type='radio']").change(function() {
  comapany_input.toggle(this.value == 'Corporation')
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <input checked="check" type="radio" value="Invididual" name="type_of_membership" id="radio-indi">
  <label class="default-link" for="radio-indi">Individual</label>&nbsp;&nbsp;&nbsp;&nbsp;
  <input type="radio" value="Institution" name="type_of_membership" id="radio-ins">
  <label class="default-link" for="radio-ins">Institution</label>&nbsp;&nbsp;&nbsp;&nbsp;
  <input type="radio" value="Corporation" name="type_of_membership" id="radio-corp">
  <label class="default-link" for="radio-corp">Corporation</label>
</div>
<div id="company-div">company-div</div>
&#13;
&#13;
&#13;