简体   繁体   中英

How I can hide div on option select

I have the below javascript which I am using the hide a div when an option is selected from a drop down list, however it is not currently working and I can't seem to figure out why.

The java script:

<script type="text/javascript">
    var $answers = $("#answers");
    $("#Type").on("change", function() {
          if ($(this).val() === "click") {
            $answers.hide();
          } else {
            $answers.show();
          }
    })
</script>

Which is to work on this part of the form:

Type:
<select name="Type" id="Type">
    <option value="choice">Multiple choice</option>
    <option value="image">Image/Video</option>
    <option value="click">Click Image</option>
</select><br>
<div id="answers">
    Correct Answer:<input type="text" name="answer"><br>
    Wrong Answer 1:<input type="text" name="wrong1"><br>
    Wrong Answer 2:<input type="text" name="wrong2"><br>
    Wrong Answer 3:<input type="text" name="wrong3"><br>
</div>

This part of a php page:

<?php 
include "connect.php"; ?>
<!DOCTYPE HTML>
<html dir="ltr" lang="en-US">

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0" />
    <title></title>
    <link rel="stylesheet" type="text/css" href="../css/_style.css" />
    <link rel="stylesheet" type="text/css" href="../css/_mobile.css" />
    <link rel="stylesheet" type="text/css" href="../css/primary-blue.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <script type="text/javascript">
        $(function () {
            $('button#showcompanys').on('click', function () {
                $('#companys').toggle("show");;
            });
        });
    </script>
    <script type="text/javascript">
        $(function () {
            $('button#showquestions').on('click', function () {
                $('#questions').toggle("show");;
            });
        });
    </script>
    <script type="text/javascript">
        $(function () {
            $('button#btnaddcompany').on('click', function () {
                $('#addcompany').toggle("show");;
            });
        });
    </script>
    <script type="text/javascript">
        $(function () {
            $('button#btnaddquestion').on('click', function () {
                $('#addquestion').toggle("show");;
            });
        });
    </script>
    <script type="text/javascript">
        var $answers = $("#answers");
        $("#Type").on("change", function () {
            if ($(this).val() === "click") {
                $answers.hide();
            } else {
                $answers.show();
            }
        })
    </script>
    <!--[if lt IE 9]>
      <link rel="stylesheet" href="../css/IE.css" />
      <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
      <![endif]-->
    <!--[if lte IE 8]>
      <script type="text/javascript" src="../js/IE.js"></script>
      <![endif]-->
</head>
<?php include "../header.php"; ?>

<button id="showcompanys" onclick="">Show/Edit Companies</button>

<button id="btnaddcompany" onclick="">Add New Company</button>
<div id="addcompany" style="display:none"><br><br><br>
    <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
        Company Name: <input type="text" name="companyname"><br>
        E-mail: <input type="email" name="email"><br>
        Number of Drivers: <input type="number" name="numdrivers"><br>
        Contact Name: <input type="text" name="contactname"><br>
        Address: <input type="text" name="address"><br>
        Phone Number: <input type="tel" name="phonenumber"><br>
        Insurance:<input type="radio" name="insurance" value="yes">Yes
        <input type="radio" name="insurance" value="no" checked>No<br>
        Number of Tests: <input type="number" name="numberoftests"><br>
        Password: <input type="password" name="password"><br>
        Notes: <input type="text" name="notes"><br>
        <input type="submit" name="addcompany" value="Create Company">
    </form>
</div>

<button id="showquestions" onclick="">Show/Edit Questions</button>

<button id="btnaddquestion" onclick="">Add New Question</button>
<div id="addquestion" style="display:none"><br><br><br>
    <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data">
        Question: <input type="text" name="question"><br>
        Category: <select name="category">
            <option value="hazardawareness">Hazard Awareness</option>
            <option value="observation">Observation</option>
            <option value="insurance">Insurance</option>
            <option value="attitude">Attitude</option>
            <option value="knowledge">Gen. Knowledge</option>
        </select><br>
        Type:<select name="Type" id="Type">
            <option value="choice">Multiple choice</option>
            <option value="image">Image/Video</option>
            <option value="click">Click Image</option>
        </select><br>
        <div id="answers">
            Correct Answer:<input type="text" name="answer"><br>
            Wrong Answer 1:<input type="text" name="wrong1"><br>
            Wrong Answer 2:<input type="text" name="wrong2"><br>
            Wrong Answer 3:<input type="text" name="wrong3"><br>
        </div>
        Question Description:<input type="text" name="description"><br>
        Correct Answer Explanation:<input type="text" name="explanation"><br>
        Image/Video:<input type="file" name="fileToUpload" id="fileToUpload"><br>
        Explanation Image:<input type="file" name="explanationfileToUpload" id="explanationfileToUpload"><br>
        Hazardous?:<input type="radio" name="hazardous" value="yes">Yes
        <input type="radio" name="hazardous" value="no" checked>No<br>
        Vehicles: <input type="checkbox" name="vehicle[]" value="car">Car <input type="checkbox" name="vehicle[]"
            value="van">Van <input type="checkbox" name="vehicle[]" value="lgv">LGV <input type="checkbox"
            name="vehicle[]" value="hgv">HGV <input type="checkbox" name="vehicle[]" value="bus">Bus<br>
        <input type="submit" name="addquestion" value="Create Question">
    </form>
</div>



<br><br><br>
<div id="companys" style="display:none">
    <?php 
    $companyssql="SELECT * FROM Companys";
    $companysresult=mysqli_query($conn, $companyssql);
    echo mysqli_error($conn);

    echo "<table border='1' width='100%'>
    <tr>
    <th>Company Name</th>
    <th>Email</th>
    <th>Driver Count</th>
    <th>Contact Name</th>
    <th>Address</th>
    <th>Phone Number</th>
    <th>Insurance</th>
    <th>Number of Tests</th>
    <th>Notes</th>
    <th></th>
    <th></th>
    </tr>";

    while($row = mysqli_fetch_array($companysresult))
    {
        echo "<tr>";
        echo "<td>" . $row['CompanyName'] . "</td>";
        echo "<td>" . $row['Email'] . "</td>";
        echo "<td>" . $row['DriverCount'] . "</td>";
        echo "<td>" . $row['ContactName'] . "</td>";
        echo "<td>" . $row['Address'] . "</td>";
        echo "<td>" . $row['PhoneNumber'] . "</td>";
        if ($row['insurance'] == 'yes'){
            echo "<td>YES</td>";
        }else{
            echo "<td>NO</td>";
        }
        echo "<td>" . $row['NumberOfTests'] . "</td>";      
        echo "<td>" . $row['Notes'] . "</td>";
        echo "<td> <form action=" . $_SERVER["PHP_SELF"] . " method='post'><input type='hidden' name='company' value=" . $row['CompanyName'] . "> <input type='submit' name='editcompany' value='Edit'> </form></td>";
        echo "<td> <form action=" . $_SERVER["PHP_SELF"] . " method='post'><input type='hidden' name='company' value=" . $row['CompanyName'] . "> <input type='submit' name='deletecompany' value='Delete'> </form></td>";
        echo "</tr>";
    }
    echo "</table>";
    ?>
    <button id="btnaddcompany" onclick="">Add New Company</button>
    <div id="addcompany" style="display:none">
        <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post">
            Company Name: <input type="text" name="companyname"><br>
            E-mail: <input type="email" name="email"><br>
            Number of Drivers: <input type="number" name="numdrivers"><br>
            Contact Name: <input type="text" name="contactname"><br>
            Address: <input type="text" name="address"><br>
            Phone Number: <input type="tel" name="phonenumber"><br>
            Insurance:<input type="radio" name="insurance" value="yes">Yes
            <input type="radio" name="insurance" value="no" checked>No<br>
            Number of Tests: <input type="number" name="numberoftests"><br>
            Number of Recruitment Accounts: <input type="number" name="numberofrecruit"><br>
            Password: <input type="password" name="password"><br>
            Notes: <input type="text" name="notes"><br>
            <input type="submit" name="addcompany" value="Create Company">
        </form>
    </div>
</div>

<div id="questions" style="display:none">
    <?php 
    $questionssql="SELECT * FROM Questions";
    if ($_GET['sort'] == 'Category')
    {
        $questionssql .= " ORDER BY Category";
    }
    elseif ($_GET['sort'] == 'Type')
    {
        $questionssql .= " ORDER BY Type";
    }
    $questionresult=mysqli_query($conn, $questionssql);
    echo mysqli_error($conn);

    echo "<table border='1' width='100%'>
    <tr>
    <th>Question</th>
    <th><a href='?sort=Category'>Category</a></th>
    <th><a href='?sort=Type'>Type</a></th>
    <th>Correct Answer</th>
    <th>Image</th>
    <th>Hazardous</th>
    <th>Vehicles</th>
    <th></th>
    <th></th>
    <th></th>
    <th></th>
    </tr>";

    while($row = mysqli_fetch_array($questionresult))
    {
        echo "<tr>";
        echo "<td>" . $row['Question'] . "</td>";
        echo "<td>" . $row['Category'] . "</td>";
        echo "<td>" . $row['Type'] . "</td>";
        echo "<td>" . $row['CorrectAnswer'] . "</td>";
        echo "<td><IMG HEIGHT=100 WIDTH=100 SRC='" . $row['ImageURL'] . "'></td>";
        if ($row['Hazardous'] == 'yes'){
            echo "<td>YES</td>";
        }else{
            echo "<td>NO</td>";
        }       
        $questionvehicles = "SELECT * FROM QuestionVehicles WHERE QuestionID = " . $row['ID'];
            $vehiclesresults = mysqli_query($conn, $questionvehicles);
        echo "<td>";
            while($vrow = mysqli_fetch_array($vehiclesresults)){
            echo $vrow['VehicleCat'] . " ";
        }
        echo "</td>";
        echo "<td> <form action=" . $_SERVER["PHP_SELF"] . " method='post'><input type='hidden' name='question' value=" . $row['ID'] . "> <input type='submit' name='editquestion' value='Edit'> </form></td>";
        echo "<td> <form action=" . $_SERVER["PHP_SELF"] . " method='post'><input type='hidden' name='question' value=" . $row['ID'] . "> <input type='submit' name='deletequestion' value='Delete'> </form></td>";
        echo "<td> <form action='preview.php' method='post' target='_blank'><input type='hidden' name='question' value=" . $row['ID'] . "> <input type='submit' name='Preview' value='Preview'> </form></td>";
        echo "<td> <form action=" . $_SERVER["PHP_SELF"] . " method='post'><input type='hidden' name='question' value=" . $row['ID'] . "> <input type='submit' name='questionreport' value='View Reports'> </form></td>";
        echo "</tr>";
    }
    echo "</table>";
    ?>

</div>
<?php include "../footer.php"; ?>

You need to wrap it into $(document).ready or move it near the end of body

<script type="text/javascript">
  $(function() { // this is the equivalent of $(document).ready(function(){
    var $answers = $("#answers");
    $("#Type").on("change", function() {
      if ($(this).val() === "click") {
        $answers.hide();
      } else {
        $answers.show();
      }
    });
  });
</script>

The reason is that when the script executes it looks for the elements, but the elements are not yet in the DOM so it can't find them. You need to either tell it to wait until it's ready or move the script at the end after all the elements are ready.

First of all... Semicolon in your script.. missing...

Use Jsfiddle for hinting what's wrong...

http://jsfiddle.net/

Second...

On dom ready... on dom load..

$(document).ready(function () {

 $(document).ready(function() { var answers = $("#answers"); $("#Type").on("change", function() { if ($(this).val() === "click") { answers.hide(); } else { answers.show(); } }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> Type: <select name="Type" id="Type"> <option value="choice">Multiple choice</option> <option value="image">Image/Video</option> <option value="click">Click Image</option> </select> <br> <div id="answers">Correct Answer: <input type="text" name="answer"> <br>Wrong Answer 1: <input type="text" name="wrong1"> <br>Wrong Answer 2: <input type="text" name="wrong2"> <br>Wrong Answer 3: <input type="text" name="wrong3"> <br> </div>

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