繁体   English   中英

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

[英]How to show and hide div elements based on the selection of radio buttons in jQuery

我想基于radio按钮showhide 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>

现在可以使用了!!!

页面加载时,您应该隐藏.studentq元素。

 $(".studentq").hide(); $('input[type="radio"]').click(function() { if ($(this).attr("value") == "student") { $(".studentq").show(); } else { $(".studentq").hide(); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <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"></option> <option value="2"></option> <option value="Other">Other</option> </select> 

我建议以下内容:

// 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演示 ,用于实验。

顺便提及,要使用普通的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演示 ,用于实验。

参考文献:

可以使用“ Id”属性代替使用“ name”属性,然后可以轻松获取选中的单选按钮的值。 {

<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();
         }
});
});

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM