What is the best way to conceal a div element on a Razor Page depending on the user's input?

How can I display the state field only when the user selects United States in the country field, and hide it otherwise? Here is the code snippet from my cshtml page:

<div class="form-group col-sm-4 mt-4">
    <label asp-for="Form.Country" class="control-label"></label>
    <select asp-for="Form.Country" class="form-control">
    <option disabled selected>Choose your Country</option>
    <option>Canada</option>
    <option>United States</option>
    <option>Mexico</option>
    </select>
    <span asp-validation-for="Form.Country" class="text-danger"></span>
</div>
<div class="form-group col-sm-4 mt-4">
    <label asp-for="Form.State" class="control-label"></label>
    <select asp-for="Form.State" asp-items="Model.States" class="form-select">
        <option disabled selected>Choose your State</option>
    </select>
    <span asp-validation-for="Form.State" class="text-danger"></span>
</div>
<div class="form-group col-sm-4 mt-4">
    <label asp-for="Form.City" class="control-label"></label>
    <input asp-for="Form.City" class="form-control" />
    <span asp-validation-for="Form.City" class="text-danger"></span>
</div>

I have looked into solutions involving JS, but I am not comfortable with it at this time. Is there a way to achieve this using razor or possibly integrate a blazor component or apply CSS?

Answer №1

It brings me great joy to see that you are able to utilize JavaScript for this task. Here is a straightforward demo with explanations, I trust it will help resolve your problem.

Start by adding an onchange() method on the first dropdown list:

<select asp-for="Form.Country" class="form-control" onchange="Select()">

Add an Id for the second dropdown list:

<div class="form-group col-sm-4 mt-4" id="demo">
    .........
</div>

Next, include the following JavaScript in your view:

@section scripts
{
    <script>
        function Select(){
            //access the element by its id
            var select = document.getElementById("Form_Country");
            //capture the selected option's text
            var index = select.selectedIndex;
            var text = select.options[index].text;
            //if the option's text is not "United States", hide the second dropdownlist
            if(text!="United States"){
                //hide the dropdownlist
                document.getElementById("demo").style.display='none';
            }else{
                //show the dropdownlist
                document.getElementById("demo").style.display='block';
            }
        }
    </script>
}

Check out the Demo: https://i.stack.imgur.com/GGkwi.gif

Answer №2

Here is the solution you need

@if (Form.Country == "UnitedStates")
{
 CODE FOR DISPLAYING STATE OPTIONS
}

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

Implement a slideshow feature that automatically changes a CSS attribute when preview images are shown

(Apologies for the perplexing title) My intention was to create a slideshow gallery, and I stumbled upon an example here: https://www.w3schools.com/howto/howto_js_slideshow_gallery.asp In this setup, you'll notice previews of images in a small bar b ...

"Getting Started with Respond.js: A Step-by-Step

I've been struggling to find clear instructions on how to properly set up respond.js. Should I just unzip it into the htdocs folder, or do I only need respond.min.js in there? Then, do I simply reference the file like this... <script src="respon ...

Get the application/pdf document that was just sent to you from the software backend

I am facing an issue with downloading a PDF file sent from the backend. Upon receiving a blob response, I notice that when I download and view the file, the sheets are empty, matching the expected number of sheets. Could this be a coding problem? Current ...

Enhance your webpage design with stylish CSS formatting using Bulma cards

My HTML output is as follows: https://i.stack.imgur.com/aBdEF.jpg It seems that the footer is not matching up with the cards... The CSS component I am using looks like this: .card-equal-height { display: flex; flex-direction: column; height: 100%; ...

Is it possible to modify the class attribute of an HTML element in PHP upon clicking an input?

In this assignment, I am restricted to using only PHP and cannot incorporate JavaScript. Currently, my code is set up to detect a post from an input type="submit" and then check for empty or filled text inputs. The code currently echoes text based on the c ...

Drupal 7 FlexSlider - alignment issue with image placement

I am encountering an issue with the Flexslider module on my Drupal 7 website. I have created a simple slider that displays 3 photos. I enabled touch screen functionality for the slider, and everything seems to be working fine except for one problem - all t ...

Guide to making a language selection wrapper using a gist script

Currently, I have a Gist file that is written in various languages but all serve the same purpose. As a result, I am interested in developing a language selection feature similar to what is found in the Google docs documentation. https://i.stack.imgur.com ...

What is the best way to prevent the body from scrolling when scrolling on a fixed div without making the body's scroll bar disappear?

Is there a way to prevent the body from scrolling while I scroll on a fixed div? I attempted using overflow:hidden for the body, which stops scrolling but causes the page to shake when the scroll bar disappears. Is there a solution that allows me to keep ...

Design elements for React and Angular JS

Is there a way to design UI components in a style that is compatible with both Angular JS and React? These two technologies will be utilized simultaneously within the same application. ...

Ignore the property if unable to parse it when using JavaScriptSerializer.Deserialize()

When deserializing JSON strings into Person objects, I use the following code snippet: JavaScriptSerializer serializer = new JavaScriptSerializer(); Person person = serializer.Deserialize<Person>(jsonString); The Person class includes an Age proper ...

Placing a list item at the beginning of an unordered list in EJS with MongoDB and Node.js using Express

What I've done: I already have knowledge on how to add an LI to UL, but it always goes to the bottom. What I'm trying to achieve: Add an LI to the top so that when my div.todos-wrapper (which has y-oveflow: hidden) hides overflow, the todos you a ...

Struggling with extracting and transferring data from a span tag to another field within the same form using selenium and python

I am struggling with an issue while running a code using selenium in Python. I am trying to extract values from span tags and store them in variables named "cap1, cap2, and cap3." After saving these values, I need to input them into another field on a web ...

Troubleshooting a JQuery accordion malfunction within a table

I am populating the data dynamically. However, the Accordion feature is not functioning correctly. JSFiddle link http://jsfiddle.net/aff4vL5g/360/ Please note: I am unable to modify the HTML structure. Current table Desired output The first accordio ...

Can you customize the "rem" values for individual Web Components when using Angular 2's ViewEncapsulation.Native feature?

I'm interested in creating a component with ViewEncapsulation.Native that utilizes Bootstrap 4 while others are using Bootstrap 3. Below is the component code with Bootstrap 4: import { Component, ViewEncapsulation } from '@angular/core'; i ...

What is causing the z-index to not function properly on my elements?

In my current code setup, I have positioned the hero image at the bottom with an overlay on top that contains text and a button. Additionally, there is a navigation bar with a z-index applied. However, I am facing an issue where the button for viewing my r ...

Image transformation not rotating the image

I'm having trouble making an image of an X rotate 180 degrees when it's hovered over. Instead of rotating, the image just moves up and to the right. What am I missing that's preventing this from looking like a smooth 180-degree spin? .bl ...

HTML - Table Layout Overlap

I'm struggling with a table layout issue in HTML and could use some assistance. The table below is displaying as overlapping in IE (please refer to the image), but it appears correctly in FF. Can anyone offer some guidance? <div> <table> ...

The loop is being controlled but the data is not being added and shown in the HTML div

I am struggling to display JSON data in an HTML div using a for loop. While my control is entering the loop, the data is not being appended and displayed in the HTML div. Here is the JSON data: [{"id":"15","FirstName":"ranjan","MiddleName":"","LastName": ...

Layering elements using the z-index property in Internet Explorer 7,

Issue with text placement in a dialog div only occurring in IE 7. To see the problem, visit this page and click on any of the text boxes on the left side. Attempts to fix by adjusting z-index in the skin.css file for div.dialogFromAndTo did not resolve ...

Error: Incorrect data input in Django calendar form

I have a DateForm class defined in my form.py file: class DateForm(forms.Form): date = forms.DateTimeField( input_formats=['%m/%d/%Y %H:%M'], widget=forms.DateTimeInput(attrs={ 'class': 'form-control dateti ...