-1

I want to Hide and Show the "City" label. Show only if I choose specific "State" if not hide it again.

  • Country=USA> State=Texas> Show the City label.
  • Country=USA> State=New York> Hide the City label

$(document).ready(function() {
  // Country dependent ajax
  $("#country").on("change", function() {
    var countryId = $(this).val();
    $.ajax({
      url: "action.php",
      type: "POST",
      cache: false,
      data: {
        countryId: countryId
      },
      success: function(data) {
        $("#state").html(data);
        $('#city').html('<option value="">Select city</option>');
      }
    });
  });

  // state dependent ajax
  $("#state").on("change", function() {
    var stateId = $(this).val();
    $.ajax({
      url: "action.php",
      type: "POST",
      cache: false,
      data: {
        stateId: stateId
      },
      success: function(data) {
        $("#city").html(data);
      }
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post">
  <div class="col-md-4">

    <!-- Country dropdown -->
    <label for="country">Country</label>
    <select class="form-control" id="country">
      <option value="">Select Country</option>
      <?php
                    $query = "SELECT * FROM countries";
                    $result = $con->query($query);
                    if ($result->num_rows > 0) {
                        while ($row = $result->fetch_assoc()) {
                            echo '<option value="'.$row['id'].'">'.$row['country_name'].'</option>';
                        }
                    }else{
                        echo '<option value="">Country not available</option>';
                    }
                    ?>
    </select>
    <br />

    <!-- State dropdown -->
    <label for="country">State</label>
    <select class="form-control" id="state">
      <option value="">Select State</option>
    </select>
    <br />

    <!-- City dropdown -->
    <label for="country">City</label>
    <select class="form-control" id="city">
      <option value="">Select City</option>
    </select>

  </div>
</form>
</div>

Action.php

<?php
// Include the database connection file
include('db_config.php');
 
if (isset($_POST['countryId']) && !empty($_POST['countryId'])) {
 
 // Fetch state name base on country id
 $query = "SELECT * FROM states WHERE country_id = ".$_POST['countryId'];
 $result = $con->query($query);
 
 if ($result->num_rows > 0) {
 echo '<option value="">Select State</option>';
 while ($row = $result->fetch_assoc()) {
 echo '<option value="'.$row['id'].'">'.$row['state_name'].'</option>';
 }
 } else {
 echo '<option value="">State not available</option>';
 }
} elseif(isset($_POST['stateId']) && !empty($_POST['stateId'])) {
 
 // Fetch city name base on state id
 $query = "SELECT * FROM cities WHERE state_id = ".$_POST['stateId'];
 $result = $con->query($query);
 
 if ($result->num_rows > 0) {
 echo '<option value="">Select city</option>';
 while ($row = $result->fetch_assoc()) {
 echo '<option value="'.$row['id'].'">'.$row['city_name'].'</option>';
 }
 } else {
 echo '<option value="">City not available</option>';
 }
}
?>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
OmerAD
  • 13
  • 4
  • Please change the snippet to have only relevant HTML – mplungjan Jan 28 '23 at 09:50
  • **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315) – Dharman Jan 28 '23 at 10:47

2 Answers2

0

try to add a condition inside the success callback function of the state dependent ajax request

success: function(data) {
    $("#city").html(data);
    if ($("#state").val() === "Texas") {
        $("#city").parent().prev("label[for='country']").show(); 
    } else {
        $("#city").parent().prev("label[for='country']").hide();  
    }
}
0

It would be easier if the label was wrapping the select or the label and select was inside a div but here you are

You could just test the state since I expect you do not have other countries with a state called Texas

This goes anywhere

$("form").on("change", "select", function() {
  const country = $("#country").val();
  const state = $("#state").val();
  const show = country === "USA" && state === "Texas";
  $("$city").toggle(show);
  $("$city").prev().toggle(show); // label
})
mplungjan
  • 169,008
  • 28
  • 173
  • 236