简体   繁体   中英

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

I want to show and hide a div based on a radio button. I have these codes, and I could not find anywhere is wrong?

<!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>

When I load the page, while the div class = "studentq" should not show since the value is empty, it still shows, and clicking on the radio buttons does not work.

Any one could help?

Thanks a lot!

Thank you chayasan!

I changed it like this:

    <!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>

It works now!!!

You should hide the .studentq element when the page loads.

 $(".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> 

I'd suggest the following:

// 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> 

External JS Fiddle demo , for experimentation.

Incidentally, to use plain JavaScript, the following would suit (although I've amended the <input> elements' HTML to use a custom data-refersto attribute to specify to which elements the <input> elements should work on:

// 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> 

External JS Fiddle demo , for experimentation.

References:

Instead of using "name" attribute you can use the "Id" attribute and then you can easily get the value of checked radio button. {

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

and then modify your jquery as given below:

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

In the same way you can check for second radio button also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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