简体   繁体   中英

Hide other divs when a radio button is clicked

Right now I have my web form working so that when a user clicks Yes it opens a new div. Well the requirements changed and the user is supposed to be only able to click Yes to one question.

Is there a way to modify my Jquery so that when a new question is choosen the previous div closes?

Below is my code.

<!doctype html>
<html>
<head>
 <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
  <script>
  jQuery(function($){

    // Prevents errors in old IE.
    if(!window.console || !window.console.log) window.console = {log: function(){}};

    // Enable debugging for complex logic.
    var debug = true;

    function checkConditions(inputs, views){
      views.each(function(){
        var view = $(this);
        var conditions = view.attr('data-view-conditions').split(',');
        var display = true;

        // Loop over all required conditions to be met.
        for(var i = 0; i < conditions.length; i++){
          var name = conditions[i].split(':')[0];
          var value = conditions[i].split(':')[1];
          var input = inputs.filter('[name="' + name + '"]:checked');

          if(debug) console.log('\nRecalculating view conditions.');

          if(!input.length){
            display = false;
            if(debug) console.log('View not show as no :checked input with the name "' + name + '" was found.');
          }else{
            if(value != undefined && input.val() != value){
              display = false;
              if(debug) console.log('View not show as no :checked input with the name "' + name + '" has the value of "' + input.val() + '". Value needed was: "' + value + '".');
            }
          }
        }

        if(display){
          view.css({display: 'block'});
        }else{
          view.css({display: 'none'});
        }

      });
    }

    $('form').each(function(){
      var form = $(this);
      var inputs = form.find('input[type="checkbox"], input[type="radio"]');
      var views = form.find('[data-view-conditions]');

      // Recalculate which views to be shown each time the inputs change.
      inputs.on('change', function(e){
        checkConditions(inputs, views);
      });

      // Check conditions to set up required view state on page load.
      checkConditions(inputs, views);
    });

  });

  </script>


<meta charset="utf-8">
<title>Submit a Ticket</title>

<link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.4.2/forms-min.css">
<style>
.myForm {
    margin-left: auto;
    margin-right: auto;
    max-width: 768px;
}
</style>
</head>

<body>
<form name="ticket1" class="pure-form pure-form-stacked myForm" action="flashpoint_processing.php" method="post">

<h2>Submit A Ticket</h2>


<legend> Your Details </legend>
<label> 
<span>First Name: </span>
    <input id="FirstName" name="FirstName" type="text" placeholder="" class="input-xlarge" required>
</label>
<label>
<label> 
<span>Last Name: </span>
    <input id="LastName" name="LastName" type="text" placeholder="" class="input-xlarge" required>
</label>
<label>  
<span> Business Name </span>
    <input id="Busname" name="Busname" type="text" placeholder="" class="input-xlarge">
 </label>

<label>Phone</label>
    <input id="Phone" name="Phone" type="text" placeholder="" class="input-xlarge" required>
<label>Extension</label>

    <input id="Ext" name="Ext" type="text" placeholder="" class="input-small">
<label> E-mail</label>
    <input id="email" name="email" type="text" placeholder="" class="input-xlarge" required>

<label>Preferred Method of Contact</label>
      <input type="radio" name="contact" id="contact-0" value="Phone" checked="checked">
      Phone
      <input type="radio" name="contact" id="contact-1" value="Email">
      Email


<label>
<legend>Issue</legend>  
<?

//Displays the four top level questions with an ID of 1
$topq = array();
$topid = array();
$results = mysql_query("select questions, ID from tbl_questions where top=1");
while($row = mysql_fetch_array($results)) {
    $topq[] = $row['questions'];
    $topid[] = $row['ID'];
    ;
};

for($i=0;$i<count($topq);$i++){
    echo "<label>";
    echo $topq[$i];
    echo "</label>";
    echo " <input type=\"radio\" name=\"top$i\" id=\"$i\"  value=\"1\" checked=\"checked\">No
      <input type=\"radio\" name=\"top$i\" id=\"yes\"  value=\"2\">Yes";
};

//Displays sub questions of Cloud my office log in issue with an ID of 2.

echo "<div data-view-conditions=\"top0:2\" style=\"background: rgba(54, 25, 25, .5)\">";
    $lowq = array();
$lowid = array();
$results = mysql_query("select questions, ID from tbl_questions where top=2");
while($row = mysql_fetch_array($results)) {
    $lowq[] = $row['questions'];
    $lowid[] = $row['ID'];
};

for($i=0;$i<count($lowq);$i++){
    echo "<label>";
    echo $lowq[$i];
    echo "</label>";
    echo " <input type=\"radio\" name=\"low$i\" id=\"$i\" value=\"1\" checked=\"checked\">No
      <input type=\"radio\" name=\"low$i\" id=\"yes\" value=\"2\">Yes";
};
    echo "</div>";

    //Displays subquestions to username and password. ID-3
echo "<div data-view-conditions=\"low0:2\" style=\"background: rgba(54, 25, 25, .5);\">";
$lowerq = array();
$lowerid = array();
$results = mysql_query("select questions, ID from tbl_questions where top=3");
while($row = mysql_fetch_array($results)) {
    $lowerq[] = $row['questions'];
    $lowerid[] = $row['ID'];
};

for($i=0;$i<count($lowerq);$i++){
    echo "<label>";
    echo $lowerq[$i];
    echo "</label>";
    echo " <input type=\"radio\" name=\"lower$i\" id=\"$i\" value=\"1\" checked=\"checked\">No
      <input type=\"radio\" name=\"lower$i\" id=\"yes\" value=\"2\">Yes";
};
    echo "</div>";

    //Dispalys Subquestions for I am having a Citrix Receiver Error with ID of 4

    echo "<div data-view-conditions=\"low1:2\" style=\"background: rgba(54, 25, 25, .5);\">";
$fourthq = array();
$fourthid = array();
$results = mysql_query("select questions, ID from tbl_questions where top=4");
while($row = mysql_fetch_array($results)) {
    $fourthq[] = $row['questions'];
    $fourthid[] = $row['ID'];
};

for($i=0;$i<count($fourthq);$i++){
    echo "<label>";
    echo $fourthq[$i];
    echo "</label>";
    echo " <input type=\"radio\" name=\"fourth$i\" id=\"$i\" value=\"1\" checked=\"checked\">No
      <input type=\"radio\" name=\"fourth$i\" id=\"yes\" value=\"2\">Yes";
};
    echo "</div>";

    //Subquestions for cloud my office desktop issue.

        echo "<div data-view-conditions=\"top1:2\" style=\"background: rgba(54, 25, 25, .5);\">";
$fiveq = array();
$fiveid = array();
$results = mysql_query("select questions, ID from tbl_questions where top=5");
while($row = mysql_fetch_array($results)) {
    $fiveq[] = $row['questions'];
    $fiveid[] = $row['ID'];
};

for($i=0;$i<count($fiveq);$i++){
    echo "<label>";
    echo $fiveq[$i];
    echo "</label>";
    echo " <input type=\"radio\" name=\"five$i\" id=\"$i\" value=\"1\" checked=\"checked\">No
      <input type=\"radio\" name=\"five$i\" id=\"yes\" value=\"2\">Yes";
};
    echo "</div>";

    //Subquestions for fileshare issue 
        echo "<div data-view-conditions=\"five0:2\" style=\"background: rgba(54, 25, 25, .5);\">";
$sixq = array();
$sixid = array();
$results = mysql_query("select questions, ID from tbl_questions where top=6");
while($row = mysql_fetch_array($results)) {
    $sixq[] = $row['questions'];
    $sixid[] = $row['ID'];
};

for($i=0;$i<count($sixq);$i++){
    echo "<label>";
    echo $sixq[$i];
    echo "</label>";
    echo " <input type=\"radio\" name=\"six$i\" id=\"$i\" value=\"1\" checked=\"checked\">No
      <input type=\"radio\" name=\"six$i\" id=\"yes\" value=\"2\">Yes";
};
    echo "</div>";

    //Subquetions for Microsoft Office  
        echo "<div data-view-conditions=\"five1:2\" style=\"background: rgba(54, 25, 25, .5);\">";
$sevenq = array();
$sevenid = array();
$results = mysql_query("select questions, ID from tbl_questions where top=7");
while($row = mysql_fetch_array($results)) {
    $sevenq[] = $row['questions'];
    $sevenid[] = $row['ID'];
};

for($i=0;$i<count($sevenq);$i++){
    echo "<label>";
    echo $sevenq[$i];
    echo "</label>";
    echo " <input type=\"radio\" name=\"seven$i\" id=\"$i\" value=\"1\" checked=\"checked\">No
      <input type=\"radio\" name=\"seven$i\" id=\"yes\" value=\"2\">Yes";
};
    echo "</div>";

        //Subquetions for System Responsiveness  
        echo "<div data-view-conditions=\"five2:2\" style=\"background: rgba(54, 25, 25, .5);\">";
$eightq = array();
$eightid = array();
$results = mysql_query("select questions, ID from tbl_questions where top=8");
while($row = mysql_fetch_array($results)) {
    $eightq[] = $row['questions'];
    $eightid[] = $row['ID'];
};

Here is a view of my live form.

http://jcsites.juniata.edu/students/bookhjr10/flashpoint/final/form.php

You could use jQuery to hide the previous div. To hide an element you could do it via changing the CSS:

$(selector).css({
    "display": "none",
    "visibility": "hidden"
});

You could also use the .hide() method (following the "write more; do less" motto):

$(selector).hide();

Now, you need to figure out where the previous form is located. This can be tricky and I recommend you read through the jQuery API ( https://api.jquery.com/ ) on finding how to locate elements. I'm not going to go into anything complex; instead I'll show you simply how to hide elements. Here is an example:

function hideSelector(element) {
    $(element).css({
        "display": "none",
        "visibility": "hidden"
    });
}

You'll need to set a 'click' event handler on the following inputs:

<input id="test1" value="foo" placeholder="foo" />
<input id="test2" value="bar" placeholder="bar" />

The actual click handlers:

$("#test1").bind("click", function () {
    hideSelector("#test2");
});
$("#test2").bind("click", function () {
    hideSelector("#test1");
});

Now, once you click on one or the other the opposite will hide. Again, there are a lot of ways you can do this and this isn't the most efficient manner but it should give you a place to start.

Here is a jsFiddle example: http://jsfiddle.net/9yy3W/

Edit: To just hide the previous input, you could do the following in your code:

inputs.on('change', function(e){
    try {
        $(this).prev('input').hide();
    } catch (e) {
        console.log(e);
    }
});

Try this code below - http://jsfiddle.net/gildonei/YxY2F/

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Submit a Ticket</title>
        <style type="text/css" media="screen">
            .hidden {
                display: none;
            }
        </style>
    </head>

    <body>
        <form name="form1" id="form1" method="post">
            <h5>Choose an option</h5>
            <h6>Question 1</h6>
            <label><input type="radio" name="question1" id="option1" value="0" checked="checked" class="has-dependent">No</label>
            <label><input type="radio" name="question1" id="option2" value="1" class="has-dependent">Yes</label>
            <hr>

            <h6>Question 2</h6>
            <label><input type="radio" name="question2" id="option1" value="0" checked="checked" class="has-dependent">No</label>
            <label><input type="radio" name="question2" id="option2" value="1" class="has-dependent">Yes</label>
            <hr>

            <h6>Question 3</h6>
            <label><input type="radio" name="question3" id="option1" value="0" checked="checked" class="has-dependent">No</label>
            <label><input type="radio" name="question3" id="option2" value="1" class="has-dependent">Yes</label>
            <hr>

            <div class="hidden" rel="question1">
                <h6>Sub option question 1</h6>
                <label><input type="radio" name="sub_question1" id="sub_option1" value="0" checked="checked">No</label>
                <label><input type="radio" name="sub_question1" id="sub_option2" value="1">Yes</label>
            </div>
            <div class="hidden" rel="question2">
                <h6>Sub option question 2</h6>
                <label><input type="radio" name="sub_question2" id="sub_option1" value="0" checked="checked">No</label>
                <label><input type="radio" name="sub_question2" id="sub_option2" value="1">Yes</label>
            </div>
            <div class="hidden" rel="question3">
                <h6>Sub option question 3</h6>
                <label><input type="radio" name="sub_question3" id="sub_option1" value="0" checked="checked">No</label>
                <label><input type="radio" name="sub_question3" id="sub_option2" value="1">Yes</label>
            </div>
        </form>

        <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
        <script type="text/javascript">
            $(function() {
                // Get the list of hidden div
                var $objDependentDiv = $('div.hidden');
                $('.has-dependent').click(function(){
                    // Gets specif dependent question
                    var $objSpecificDiv = $('div[rel="' + $(this).attr('name') + '"]');

                    // Force all sub question div to be hidden
                    $objDependentDiv.addClass('hidden');

                    // Shows specific subquestion div
                    $objSpecificDiv.removeClass('hidden');
                });
            });
        </script>
    </body>
</html>

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