如何根据jQuery中单选按钮的选择显示和隐藏div元素

时间:2015-08-14 17:28:59

标签: javascript jquery html

我希望基于show按钮hideradio div。 我有这些代码,我找不到任何错误的地方?

<!DOCTYPE html>
<html lang="en">

<head>
    <script>
        $(document).ready(function() {
            $('input[type="radio"]').click(function() {
                if ($(this).attr("value") == "student") {
                    $(".studentq").show();
                }
            });
        });
    </script>
</head>

<body>
    <label name="Q2">I am a:</label>
    <input type="radio" name="A2" value="student">Student
    <input type="radio" name="A2" value="parent">Parent

    <div class="studentq">

        <label name="Q3">If Student, High School Graduation Year:</label>
        <select name="A3">
            <option disabled selected> -- select an option -- </option>
            <option value=<?php echo $beforeyear2;?>>
                <?php echo $beforeyear2;?>
            </option>
            <option value=<?php echo $beforeyear1;?>>
                <?php echo $beforeyear1;?>
            </option>
            <option value="Other">Other</option>
        </select>

    </div>
</body>

</html>

当我加载页面时,由于值为空,div class = "studentq"不应显示,但它仍然显示,并且单击单选按钮不起作用。

任何人都可以提供帮助吗?

非常感谢!

谢谢chayasan!

我这样改了:

    <!DOCTYPE html>
    <html lang="en">
    <head>
   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script>

        $(document).ready(function() {
            $(".studentq").hide();
                $('input[type="radio"]').click(function() {
                    if ($(this).attr("value") == "student") {
                        $(".studentq").show();
                    }
                });
            });
        </script>
    </head>
    <body>

    <label name = "Q2" >I am a:</label>
    <input type = "radio" name = "A2" value = "student" >Student
    <input type = "radio" name = "A2" value = "parent" >Parent

    <div class ="studentq">

    <label name = "Q3" >If Student, High School Graduation Year:</label>
    <select name = "A3" >
    <option disabled selected> -- select an option -- </option>
    <option value ="1">2014</option>
    <option value ="2">2015</option>
    <option value ="Other" >Other</option>
    </select>

    </div>
    </body>
    </html>

现在可以使用!!!

2 个答案:

答案 0 :(得分:1)

我建议如下:

// selecting the <input> elements of type=radio,
// and binding the anonymous function to handle
// the change event:
$('input[type=radio]').on('change', function() {

  // caching the reference to the changed <input>:
  var check = this;

  // selecting the elements with the class of
  // 'parentOrStudent' and hiding them all;
  // using the filter() method:
  $('.parentOrStudent').hide().filter(function() {

    // to keep only those elements for whom the following is true,
    // the checkbox is checked and the .parentOrStudent element
    // contains the value ('parent' or 'student') in its classList:
    return check.checked && this.classList.contains(check.value);

  // we show only those elements retained in the collection:
  }).show();

// we then trigger the change event to fire the function
// on page load:
}).change();

$('input[type=radio]').on('change', function() {
  var check = this;
  $('.parentOrStudent').hide().filter(function() {
    return check.checked && this.classList.contains(check.value);
  }).show();
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<fieldset>
  <legend>I am a:</legend>
  <label>
    <input type="radio" name="A2" value="student" />Student</label>
  <label>
    <input type="radio" name="A2" value="parent" />Parent</label>
</fieldset>

<fieldset class="parentOrStudent student">

  <legend>If Student, High School Graduation Year:</legend>
  <select id="A3">
    <option disabled selected>-- select an option --</option>
    <option value="1"></option>
    <option value="2"></option>
    <option value="Other">Other</option>
  </select>

</fieldset>


<fieldset class="parentOrStudent parent">

  <legend>If parent, some other pertinent question:</legend>
  <select id="A4">
    <option disabled selected>-- select an option --</option>
    <option value="1"></option>
    <option value="2"></option>
    <option value="Other">Other</option>
  </select>

</fieldset>

外部JS Fiddle demo,用于实验。

顺便说一句,要使用纯JavaScript,以下内容适合(尽管我已修改了<input>元素'HTML以使用自定义data-refersto属性来指定<input>哪些元素元素应该起作用:

// creating a named function to handle the events:
function toggleElements() {

  // caching the changed <input> element:
  var check = this,

  // caching the elements that should be affected, by
  // concatenating a '.' with the value held in the 
  // changed-element's 'data-refersto' attribute:
    refersTo = document.querySelectorAll('.' + check.dataset.refersto);

  // if we retrieved any elements in the 'refersTo' variable:
  if (refersTo && refersTo.length) {

    // we use Array.prototype.forEach() to iterate over
    // the collection, and use Function.prototype.call()
    // to use the Array-like collection (refersTo) with
    // an Array method:
    Array.prototype.forEach.call(refersTo, function(node) {

      // if the changed element is checked, and
      // the current refersTo node (here referred to
      // as 'node') contains a class equal to the value
      // of the changed element:
      if (check.checked && node.classList.contains(check.value)) {

        // we set the display to 'block' (to show):
        node.style.display = 'block';
      } else {

        // otherwise we set the display to 'none' (to hide):
        node.style.display = 'none';
      }
    });
  }
}

// we use document.querySelectorAll() to retrieve all <input>
// elements of type=radio with a 'date-refersto' attribute:   
var radioInputs = document.querySelectorAll('input[type=radio][data-refersto]'),

// creating a new Event, in order that we can trigger the
// 'change' event:
  changeEvent = new Event('change');

// iterating over the found <input> elements (as above):
Array.prototype.forEach.call(radioInputs, function(input) {

  // adding an event-listener for the 'change' event,
  // assigning the toggleElements() function to
  // handle this event:
  input.addEventListener('change', toggleElements);

  // triggering the 'change' event on page-load:
  input.dispatchEvent(changeEvent);
});

function toggleElements() {
  var check = this,
    refersTo = document.querySelectorAll('.' + check.dataset.refersto);

  if (refersTo && refersTo.length) {
    Array.prototype.forEach.call(refersTo, function(node) {
      if (check.checked && node.classList.contains(check.value)) {
        node.style.display = 'block';
      } else {
        node.style.display = 'none';
      }
    });
  }
}

var radioInputs = document.querySelectorAll('input[type=radio][data-refersto]'),
  changeEvent = new Event('change');

Array.prototype.forEach.call(radioInputs, function(input) {
  input.addEventListener('change', toggleElements);
  input.dispatchEvent(changeEvent);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<fieldset>
  <legend>I am a:</legend>
  <label>
    <input type="radio" name="A2" value="student" data-refersto="parentOrStudent" />Student</label>
  <label>
    <input type="radio" name="A2" value="parent" data-refersto="parentOrStudent" />Parent</label>
</fieldset>
<fieldset class="parentOrStudent student">
  <legend>If Student, High School Graduation Year:</legend>
  <select id="A3">
    <option disabled selected>-- select an option --</option>
    <option value="1"></option>
    <option value="2"></option>
    <option value="Other">Other</option>
  </select>
</fieldset>
<fieldset class="parentOrStudent parent">
  <legend>If parent, some other pertinent question:</legend>
  <select id="A4">
    <option disabled selected>-- select an option --</option>
    <option value="1"></option>
    <option value="2"></option>
    <option value="Other">Other</option>
  </select>
</fieldset>

外部JS Fiddle demo,用于实验。

参考文献:

答案 1 :(得分:1)

而不是使用&#34; name&#34;你可以使用&#34; Id&#34;属性然后您可以轻松获取已选中单选按钮的值。 {

<input type="radio" id="rdStudent" value="student" name="A2"/>
<input type="radio" id="rdParent" value="parent" name="A2"/>

然后修改你的jquery,如下所示:

$(document).ready(function(){
(".studentq").hide();
$("#rdStudent").click(function(){
      if("#rdStudent").val()=="student")
       {
           $(".studentq").show(); 
       }
       else{
            $(".studentq").hide();
         }
});
});

同样,您也可以检查第二个单选按钮。