Display Button and Div when Event occurs in Asp.net core using Razor Pages

I am currently working on a project that involves two dropdown menus: one for Categories and the other for SubCategories. Within a partial view named _CreateProject, I have set up an html form to facilitate the creation of new projects. My goal is to have a button that, when clicked, displays the form for creating a new project. However, I only want the "Create Project" button to be visible after a category and subcategory are selected, and I want the _CreateProject partial to display only upon clicking the button.

Despite my attempts to label the divs as hidden and then reveal them using $(#id).show(), the divs remain concealed.

Below are the scripts where I have attempted to reveal the buttons:

<script>
                    //Populate SubCategory when Category changes
                    $(function () {
                        $("#Category").on("change", function () {
                            var categoryId = $(this).val();
                            $("#SubCategory").empty();
                            $("#SubCategory").append("<option value=''>---Select Subcategory---</option>");
                            $.getJSON(`?handler=SubCategories&categoryId=${categoryId}`, (data) => {
                                $.each(data, function (i, item) {
                                    $("#SubCategory").append(`<option value="${item.subCategoryId}">${item.subCategoryName}</option>`);
                                });
                            });
                        });

                        //try to show #partial on button click
                        $("#projectButton").click(function () {

                            $("#partial").show(); //try to reveal partial here

                        });



                        $("#SubCategory").on("change", function () {
                            $("#projectButton").show();  //try to show button here
                            var SubCategoryId = $(this).val;
                            $("#ProjectId").empty();
                            $.getJSON(`?handler=Projects&SubCategory=${SubCategoryId}`, (data) => {
                                             //...

Here's the button along with the div containing the partial:

<div hidden id="projectButton">
    <button type="submit" class="btn btn-default">New Project</button>
</div>

<div id="partial" hidden>
    <partial name="_CreateProject"/>
</div>

For reference, here are the Category and SubCategory sections:

<label asp-for="Category">Category:  </label>
<select asp-for="Category" asp-items="Model.categorylist">
    <option value="">---Select Category---</option>
</select>


<label asp-for="SubCategory">Subcategory:</label>
<select asp-for="SubCategory"><option value="">---Select Subcategory---</option></select>
public void OnGet()
{

            categorylist = new SelectList(categoryService.GetCategories(), nameof(Category.CategoryId), nameof(Category.CategoryName));

}

//called by first jQuery
public JsonResult OnGetSubCategories()
{
            UserId = Convert.ToInt32(HttpContext.Session.GetString("SessionUserId"));
            return new JsonResult(categoryService.GetSubCategories(Category.CategoryId, UserId));

}

Any advice or suggestions on how to achieve this functionality would be greatly appreciated. I'm still learning jQuery, so I suspect there might be an error in my approach. Thank you!

Answer №1

To illustrate your scenario with static data, here is a simple demonstration that confirms the validity of your initial concept: https://jsfiddle.net/f7j6vgmo/.

However, introducing Bootstrap into the mix causes it to malfunction: https://jsfiddle.net/f7j6vgmo/1/

This issue seems to stem from Bootstrap applying !important to the CSS definition for the hidden attribute. You can observe this in the browser's element inspector when examining elements labeled as hidden (even after executing a .show() command):

[hidden] {
    display: none!important;

The origin of this rule is identified as reboot.scss, which is a component of Bootstrap. Consequently, the display:none; defined by the rule takes precedence over the display:block established by the .show() method. (Typically, setting the display property overrides the hidden attribute, as explained here).

An easy solution is to substitute the hidden attributes with style="display:none;".

Demonstration: https://jsfiddle.net/f7j6vgmo/2/

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

Switch up the text when the image link is being hovered over

Is there a way to change the text color of the "a" tag when it is not wrapping the img link? <li> <a href="# WHEN I HOVER THIS IMG LINK I WANT A TAG BELOW TO CHANGE COLOR"> <img alt="Franchise 16" src="#"></img> < ...

Adding some extra space inside a flex container using Bootstrap's padding

When attempting to use padding within a d-flex container to separate elements that are placed inline due to the d-flex class, I encountered an issue where the padding was not being applied and did not change anything. If I do not utilize the d-flex class, ...

Improving search functionality with autocomplete in EasyAdmin 3.3 filter options

Is there a quick solution in easyadmin 3.3 to implement an autocomplete feature for filters? I have successfully used it in forms, but encountering an undefined error with filters. public function configureFields(string $pageName): iterable { r ...

Using JQuery to enhance the functionality of ajax-loaded content

Having difficulty implementing a more/less functionality in an ajax-loaded section of a webpage. I customized a script found at http://jsfiddle.net/gDvyR/72/, primarily by adding "on" functionality to address the ajax issue. You can view the modified ver ...

I am encountering difficulties in accessing my component's property within the corresponding template while working with Angular 5

When I call an HTTP POST method to retrieve table names from the backend, I attempt to display them in the template using ngFor. However, the table names are not appearing on the screen. The tNames property is inaccessible in the template. As a beginner i ...

Sending Django log files via AjaxORTransmitting Django log

After following a solution on Stack Overflow about reading log files in Django from /var/log/gateway, I successfully displayed the file content in the terminal. Here is an example: 2013-05-09T11:15:02.539091+08:00 localhost gateway[5205]: System starting ...

What's the reason behind this file not opening?

When I try to insert this code into files index.html, style.css, and app.js, the page refuses to open. The browser constantly displays a message saying "The webpage was reloaded because a problem occurred." I am using a MacBook Air with macOS Big Sur and a ...

What is the best way to make a message appear only when the browser screen is smaller?

I am struggling to make a message appear only when the screen is resized. It's puzzling me why my current approach isn't yielding the desired result. Instead of displaying the message only on a shrunk screen, it shows up all the time. I can confi ...

Ensure each alternate div has a unique background hue

While attempting to use CSS to assign a different background color to every second div element, I encountered an issue where both divs were affected when using (odd) and none when using (even). How can this be explained? .hoverDiv:nth-child(odd) { ba ...

The navigation bar triggers the opening of all icon menus in their designated positions at the same time

This code snippet represents the navigation bar for an admin user, featuring 3 icons: navigation menu, user menu, and manage button icons. The problem arises when clicking on any of these icons, as all dropdown items from each icon are displayed in their ...

Ways to apply the .not selector efficiently in jQuery

I have a situation with two separate divs, one named task1 and the other named task2. Each of these tasks contains panels with various names. Within task2, there is a duplicate name (Greg), who also belongs to the duplicate class. I'm trying to figure ...

What could be causing the issue of $.ajax being undefined while utilizing jQuery in Node.js?

I'm currently testing a module on Node.js that is meant for client-side use. In order to make $.ajax work, I need some guidance. To begin with, I have installed jQuery on the project using: $ npm install jQuery Despite this, when I try to access $. ...

How to align the navbar toggle button and list items to the right in Bootstrap 5

I'm struggling with a simple html page that has a fixed navbar at the top. Everything looks great when viewed in full-screen mode, with centered links. However, when the page size is reduced, it collapses to a toggle button on the left side. What I re ...

Tips on adding a hotspot to an image using jQuery for selecting a specific area

I am looking to divide an image into multiple sections. When hovering over each section, I want a tag to be displayed. This should also work smoothly with responsive design. Can anyone assist me with this? Thanks! ...

Is it possible to consistently show the placeholder in mat-select regardless of the item currently selected?

I am looking to keep the mat-select element displaying the placeholder at all times, even if an option has been selected. Below is my HTML code: <mat-select [formControlName]="'language'" placeholder="Language"> <mat-option value=" ...

What is the best way to reset the selected option in Vue.js when clicking on a (x) button?

Is there a way to create a function or button specifically for clearing select option fields? I attempted using <input type="reset" value="x" /> However, when I clear one field, all fields end up getting cleared. Should I provide my code that incl ...

Is there a way to transition an element from a fixed layout position to an absolute layout position through animation?

I am looking to create a dynamic animation effect for a button within a form. The goal is for the button to move to the center of the form, while simultaneously undergoing a horizontal flip using a scale transform. During the midpoint of this animation, I ...

The password-protected HTML blog remains hidden until the correct entry is entered into the password box, causing

After successfully creating a password redirect page where entering the correct password redirects you to another URL (psswrdtest.tumblr.com with the password as correctpsswrd, redirecting to google.com*), I attempted to improve it by making the password p ...

The setStyle() method in JavaFX is like CSS Selectors

Is it possible to bind CSS files to style JavaFX components and also change properties dynamically in code? I'm struggling with the setStyle() method as there's limited documentation available on how to use it effectively. Instead of modifying t ...

Adjust the height of the Iframe to match the content within it

After conducting my research, I have not been able to find a solution. Although I am not an expert in jQuery, it seems that the code is not functioning properly. Within the iframe are links that expand when clicked to display content. However, the height o ...