Ways to display or conceal form controls when altering select box choices

In my HTML, I have two select boxes: the first for Country and the second for City. The requirement is to display a textbox when a user selects a country other than Pakistan and show a dropdown list for city if the user selects Pakistan from the country dropdown.

Below is the code snippet that I attempted:

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
  <div class="form-group col-md-3">
    <label for="cc-payment" class="control-label mb-1">Birth Country</label>
    <select class="form-control" name="Birth_Country" id="Birth_Country" style="color: black;" required>
      <option value="">Please Select Birth Country</option>
      <?php
      $sel_cus = "select Country_Name from personal_country_name Order By Country_Name";
      $res_cus = mysqli_query($connection, $sel_cus);
      while ($row = mysqli_fetch_array($res_cus)) {?>
      <option value="<?php echo $row['Country_Name'];?>"><?php echo strtoupper($row['Country_Name']);?></option>
      <?php
      }
      ?>
    </select>
  </div>
  
  <div class="form-group col-md-3">
    <label for="cc-payment" class="control-label mb-1">Birth City</label>
    
    <select class="form-control" name="Birth_City" id="Birth_City" style="color: black;" required>
      <option value="">Please Select Birth City</option>
      <?php
        $sel_cus = "select city_name from personal_city_name order By city_name";
        $res_cus = mysqli_query($connection, $sel_cus);
        while ($row = mysqli_fetch_array($res_cus)) {?>
          <option value="<?php echo $row['city_name'];?>"><?php echo strtoupper($row['city_name']);?></option>
        <?php
        }
      ?>
    </select>
    
    <input type="text" autocomplete="off" onkeyup="this.value = this.value.toUpperCase();" class="form-control" name="Other_Birth_City" id="other" style="color: black;" value="<?php echo $data['Birth_City']?>" required data-toggle="tooltip" title="Birth City" placeholder="Birth City"/>
  </div>

  <button type="submit" class="btn btn-primary pull-right" style="margin-right: 430px; width: 105px; height: 42px; margin-top: 22px;" value="Save" name="Save" id="Save">Save</button>
</form>

Answer №1

Check out this Jquery snippet:

$(function(){
$("#state").hide();
});
$("#country").change(function(){
if($("#country").val() !="" )
{
$("#state").show();
} else {

$("#state").hide();
}
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="country">
<option value="">Select a country</option>
<option value="1">Country 1</option>
<option value="2">Country 2</option>
</select>

<select id="state">
<option value="">Select a state</option>
<option value="1">State 1</option>
<option value="2">State 2</option>
</select>

Answer №2

Provided an illustrative example tailored to meet your specific requirements. Below are the steps you need to follow:

  1. Conceal both controls
  2. Activate control based on the selection value

function hideBoth() {
  $('#cityText').hide();
  $('#city').hide();

}
$(document).ready(function() {
  $('#country').on('change', function() {
    hideBoth();
    var country = $.trim(this.value).toLowerCase();
    if (country !== "pakistan") {
      $('#cityText').show();
    } else {
      $('#city').show();
    }
  });
});
.hide {
  display: none;
}

.show {
  display: inline;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<select id="country">
  <option value="">Select</option>
  <option value="USA">USA</option>
  <option value="UK">UK</option>
  <option value="Pakistan">Pakistan</option>
  <option value="India">India</option>
  <option value="Iran">Iran</option>
  <option value="Nepal">Nepal</option>
</select>

<select id="city" class="hide">
  <option value="">Select</option>
  <option value="1">City 1</option>
  <option value="2">City 2</option>
  <option value="3">City 3</option>
  <option value="4">City 4</option>
  <option value="5">City 5</option>
  <option value="6">City 6</option>
</select>

<input type="text" placeholder="Enter your city" class="hide" id="cityText" />

Answer №3

Utilize jquery for dynamic content changes

<script>
$(document).ready(function(){
$("#Birth_Country").onchange(function(){
$country = $('#Birth_Country').val();
if ($country == "Pakistan") {
$("#Birth_City").show();
$("#other").hide();
}else {
$("#other").show();
$("#Birth_City").hide();
}
}
});
</script>

Remember to include the script file in PHP along with the jQuery file

<script src="https://code.jquery.com/jquery-3.4.1.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can you suggest a simple method for implementing the "componentDidUpdate()" lifecycle method using just JavaScript?

I've been curious about replicating the componentDidUpdate() lifecycle method in JavaScript on my own. It got me thinking, how did React and Vue.JS create their own lifecycle methods? I attempted to study the minified version of Vue.JS but found it qu ...

What is the functionality of background attachment fixed?

I am curious about how background images behave when the background-attachment property is set to fixed. Here are my questions: If I set a background image for a div with dimensions of 500px by 500px and add a 1px solid red border, then apply backgro ...

Trouble with tab switching across multiple cards

I have been working on an app that generates multiple cards with 3 tabs on each card. However, I am facing an issue with tab switching. The tab switching works fine on the first card, but when I try to switch tabs on other cards, it still affects the tabs ...

Using Jquery to add links that open in a new tab

I have a client who runs a WooCommerce WordPress site and they want the product image/link on the category page to open in a new tab when clicked. I have been attempting to use jquery to achieve this with no success. As I am relatively new to jquery, any a ...

Tips for revealing a link after the user clicks on the submit button

I am looking to set up a webpage that will display a hyperlink after the submit button is clicked. For example, 1) wedding 2) engagement 3) birthday All three items are checkbox buttons and there is a textbox to input the budget. After clicking the sub ...

How can I redirect the page in CodeIgniter after successfully validating?

Currently, I am utilizing CodeIgniter for my project's development and implementing field validation using Bootstrap validator. Although the Bootstrap validator is functioning properly, I am encountering an issue. Upon successful validation, I expect ...

What is the difference in performance between using named functions versus anonymous functions in Node.js?

Currently, I am working on a Node.js app and was initially using anonymous functions for callbacks. However, after referring to the website callbackhell.com, I discovered that using named functions is considered best practice for coding. Despite switching ...

When forcibly closing a window, the disconnect event for Socket.IO sockets may not trigger as expected

Currently in the process of creating chat rooms with Socket.io. I've had good success so far, as it's user-friendly and well-documented. However, I've noticed that if I reload the page, wait for the socket to connect, and then close the w ...

Combining a random selection with a timer in JavaScript for a dynamic user experience

Currently, I am developing a Twitter bot using JavaScript, Node.js, and the Twit package. The goal is for the bot to tweet every 60 seconds with a randomly selected sentence from an array. When testing the timer and random selection function individually, ...

Is it a commonly recommended method to nest fxLayout containers?

Recently, I ventured into using Angular Flex for the first time and I find myself a bit unsure about the nesting of layout containers. The issue arises when dealing with a navigation tag that triggers an angular-material sidenav opening to the left, pushin ...

Understanding how to access POST content in Meteor.js is an important aspect

In my Meteor app, I am trying to retrieve data using POST requests. Here is the code snippet I am using on the server side: __meteor_bootstrap__.app.stack.splice (0, 0, { route: '/input', handle: function(req, res, next) { req.on(' ...

Enhancing a React User Interface Element

Looking for advice on enhancing a UI component that receives an object containing various data types such as string, int, boolean, arrays, and objects, and displays them all. Below is an example of the object. PS: The object can also be found in the codesa ...

Strategies for aligning the initial lines of text vertically within a table cell

I am faced with a unique challenge involving a table where the first cell contains the word "name" and the second cell contains some text. Sometimes, this text may include embedded images. The issue arises when an image appears on the first line of the tex ...

Enhance your figures with a unique Javascript magnifying tool that works seamlessly across all browsers

After searching the web for magnifying glasses, I found that most only work for one picture. So, I took matters into my own hands and created a magnifying glass that can magnify all pictures within a specific div. It functions perfectly on Chrome browser b ...

Determine whether a div contains any child elements

I am working on a piece of code that checks for the presence of the class "wrong" in any of my divs, and if found, displays a jQuery UI dialog box. My goal now is to enhance this code by adding a condition where it also checks for empty divs before showing ...

Concealing Images in HTML Without Reserving Space for Them

Our task is to create a website here: I tried hiding elements using display: none; However, I ended up with a large blank space. https://i.sstatic.net/B2E8Y.jpg This is the HTML code: <h1>OUR PORTFOLIO</h1><div class="subtext-top"& ...

Incorporate a notification into the Windows notification center without it being visibly displayed on the desktop

I am currently developing an Electron application that includes a custom Notification feature. This feature involves html5 divs appearing and disappearing as necessary on a frameless, transparent, always-on-top window. Although the feature works well, I s ...

How can I modify the URL path using react-i18next?

I've been grappling with this problem for the past few days. My React app is causing me some trouble as I try to implement multilingual support using i18next. I aim to modify the URL path based on the selected language, such as http://localhost:3000/e ...

The excessive load time of my ajax request within a for loop is causing delays when calling a php file

My Ajax request is taking a long time to load as I'm calling the ajax function from 1 to 3000. It queries the database for each value and returns if the value exists in the database. function GetData(id) { id = id; jQuery.ajax({ type: "GET", ...

Angular not functioning properly with alert windows

Here is a snippet of code where I am attempting to create an alert when a button is clicked: <!DOCTYPE html> <html> <head> <title></title> </head> <body ng-app> <button ng-click="alert('test')"> ...