toggleclass('d-block')多输入单选不起作用

时间:2019-07-17 21:08:20

标签: javascript jquery bootstrap-4

我们有很多.html_element { float: right; }

radio input
 
function showReferal() {
   document.querySelector('#referral_code').classList.remove('d-none');
}
 

  

当我单击 <div class="form-group row d-none" id="referral_code"> <label for="referral_code">Referral Code</label> <div class="col-md-10"> <input id="referral_code" type="text" class="form-control" name="referral_code"> </div> </div> <input class="form-check-input" type="radio" name="familiar" id="google" value="1"> <input class="form-check-input" type="radio" name="familiar" id="friends" value="2"> <input class="form-check-input" type="radio" name="familiar" id="advertising" value="3"> <input class="form-check-input" type="radio" name="familiar" id="marketer" value="4" onclick="showReferal()">时,应该显示#marketer

当我单击#referral_codeadvertisinggoogle时,friends必须隐藏。仅显示referral_code

2 个答案:

答案 0 :(得分:1)

您需要从每个单选按钮调用该函数。

function showReferal(show) {
  var refCode = document.querySelector('#referral_code');
  if (show) {
    refCode.classList.remove('d-none');
  } else if (refCode.classList.value.indexOf('d-none') === -1) {
    refCode.classList.add('d-none');
  }
}
.d-none {
  display: none
}
<div class="form-group row d-none" id="referral_code">
  <label for="referral_code">Referral Code</label>
  <div class="col-md-10">
    <input id="referral_code" type="text" class="form-control" name="referral_code">
  </div>
</div>
<input class="form-check-input" type="radio" name="familiar" id="google" value="1" onclick="showReferal(false)">
<input class="form-check-input" type="radio" name="familiar" id="friends" value="2" onclick="showReferal(false)">
<input class="form-check-input" type="radio" name="familiar" id="advertising" value="3" onclick="showReferal(false)">
<input class="form-check-input" type="radio" name="familiar" id="marketer" value="4" onclick="showReferal(true)">

答案 1 :(得分:1)

与Alex Kudryashev的答案类似,但是您可以使用内置的toggle方法,而不用编写if语句。

function showReferal(show) {
  var refCode = document.querySelector('#referral_code');
  refCode.classList.toggle('d-none', !show); 
}
.d-none {
  display: none
}
<div class="form-group row d-none" id="referral_code">
  <label for="referral_code">Referral Code</label>
  <div class="col-md-10">
    <input id="referral_code" type="text" class="form-control" name="referral_code">
  </div>
</div>
<input class="form-check-input" type="radio" name="familiar" id="google" value="1" onclick="showReferal(false)">
<input class="form-check-input" type="radio" name="familiar" id="friends" value="2" onclick="showReferal(false)">
<input class="form-check-input" type="radio" name="familiar" id="advertising" value="3" onclick="showReferal(false)">
<input class="form-check-input" type="radio" name="familiar" id="marketer" value="4" onclick="showReferal(true)">