Display or conceal a division underneath a dropdown menu based on selections retrieved from a SQL Server database

Presented here is my JavaScript code.

function appendItemforPurchaseOrder() {
    debugger

    var rowNumber = parseInt($(".itemmapContainer").attr("data-rownumber"));
    rowNumber = isNaN(rowNumber) ? 1 : rowNumber + 1;

    var addNewItemDetailHtml = "<div class='col-lg-12 col-md-12 col-sm-12 col-xs-12 itemmapWrapper custom-paaddingnone form-group'\
                               id='itemmapWrapper" + rowNumber + "' data-rowNumber='" + rowNumber + "' >";

    addNewItemDetailHtml += "<div class='col-lg-10 col-md-10 col-sm-10 col-xs-10 custom-paaddingnone form-group'>\
                                <div class='col-lg-1 col-md-1 col-sm-1 col-xs-1 custom-paaddingnone text-center'>" + rowNumber + "\
                                </div>\
                                <div class='col-lg-11 col-md-11 col-sm-11 col-xs-11 custom-paaddingnone'>\
                                    <div class='col-lg-4 col-md-4 col-sm-4 col-xs-4 custom-paaddingleft' onclick='createUserJsObject.hideRemove();'>\
                                        <select class='form-control' id = 'itemid"+ rowNumber + "' ></select></div>\
                                    **<div class='col-lg-2 col-md-2 col-sm-2 col-xs-2 custom-paaddingleft' style='display: none'>\
                                        <select class='form-control' id = 'hotelid"+ rowNumber + "' ></select></div>\**
                                </div> </div>";

    addNewItemDetailHtml += "</div>";

    $(".itemmapContainer").attr("data-rownumber", rowNumber);
    $(".itemmapContainer").append(addNewItemDetailHtml);
    intialize_itemDropDown(rowNumber);
}

Upon selecting an option from the initial Selection Box with ID itemid, the secondary Selection Box (with ID hotelid) should be displayed. Below is the function that manages the dropdown options. The hideRemove function is supposed to reveal the hidden div, but it seems to be malfunctioning.

function intialize_itemDropDown(rowNumber) {
    $.ajax({
        type: "GET",
        url: "/Item/GetAllItems/",
        cache: false,
        success: function (data) {
            debugger
            var countryHTMLString = "<option value ='0'>Select Item</option>";
            if (data.isSucess) {
                $.each(data.data, function (index, item) {
                    countryHTMLString += "<option value ='" + item.itemid + "'>" + item.itemname + " , " + item.companyname + "</option>";
                });
            }
            $("#itemid" + rowNumber + "").html(countryHTMLString);
        }, error: function (err) {
            debugger
        }
    });
}

function hideRemove() {
    $("#itemid").change(function () {
        $("#hotelid").hide();
        $("#" + $(this).val()).show();
    });
};

Answer №1

Here is the issue:

onclick='createUserJsObject.hideRemove();'

Although this line correctly calls the hideRemove() function, it only attaches the event. This means that you have to click first and then change the option in select to either hide() or show(). To address this, make a small adjustment to your hideRemove() like so:

function hideRemove() {
       $('body').on('change',
            '#itemid',
            function() {
               $("#hotelid").hide();
               $("#" + $(this).val()).show();
            });
}

Since you are modifying the DOM, ensure that you attach your events to the new elements added on the body.

In this scenario, I recommend calling the hideremove() after this line:

 $(".itemmapContainer").append(addNewItemDetailHtml);

Lastly, consider removing this part. Give it a try:

onclick='createUserJsObject.hideRemove();'

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

Connecting multiple promises using an array

After making an ajax call to retrieve an array of results, I have been attempting to process this data further by making additional ajax calls. However, when using Promise.all() and then continuing with .then(function(moreData){}), I noticed that the moreD ...

Error message encountered when deploying a Discord bot on Heroku: "SyntaxError: Unexpected token '??='"

I encountered an issue when trying to deploy a Discord bot that I created using Node.js on Heroku. The error message is as follows: 2021-11-05T00:00:10.334347+00:00 app[web.1]: > node . 2021-11-05T00:00:10.334348+00:00 app[web.1]: 2021-11-05T00:00:10.3 ...

How to include a key-value pair to a JSON object within an array using JavaScript

I am looking to include the following functionality in the JSON data provided below: "Check if the key name default exists, and if it does, add another key within the same object => ("pin" : 91)." I have attempted to achieve this using the code snippet b ...

What to do when faced with the error message "Nodemon is not recognized as a command"?

When I try to run npm start, my Node.js is not starting. The error message displayed is: 'nodemon' is not recognized as an internal or external command, operable program or batch file. I have double-checked my environment path and also tried r ...

Refreshing a single HTML element in ASP.NET MVC - the simple way!

Recently, I put together an image gallery using the unite gallery jquery plugin and now I want to change up the images it displays. My plan is to have a button labeled "art" that, when clicked, triggers a function to update the directory path and load ne ...

Show the chosen value from the dropdown menu on all JSP pages

I have a header.jsp file containing a dropdown box labeled "Role". This header.jsp is designed to be included in all other JSP files using a directive. Once a user logs in, they are directed to a homepage where they must select a value from the dropdown ...

Is there a way to remove the spacing that browsers automatically add to <input> elements?

Take a look at this example: http://jsfiddle.net/JPQxX/ I tested this in both Chrome and Firefox. In both browsers, there seems to be a small 1-2px margin between the two input elements. I am looking for a solution to make these two elements touch without ...

Vue parent component not receiving events properly

Referring to these sources: Forum Post Stack Overflow Question In my project, I am utilizing: CodeSandbox Example The setup involves the parent component listening for events emitted by a child component: mounted() { this.$on("edit-category& ...

Preserve StepContent information within Material-ui Stepper during updates to the active step

I have a Stepper component with multiple steps, each containing several TextFields. The issue is that material-ui unmounts the step contents when you switch steps, causing all the data in the TextFields to be lost. My question is: Is there a way to prese ...

A conflict with the Ajax file is causing an automatic logout

In my Rails application, there is a page with a table that uses partial AJAX to increase the capacity attribute in a time entity. You can view the visual representation of the table here. By clicking the plus/minus button, the capacity attribute increases ...

Understanding the Intrinsic Dimensions of Replaced Elements in CSS

I'm currently facing some challenges with the CSS Intrinsic & Extrinsic Sizing Module Level 3, specifically chapter 4.1 on Intrinsic Sizes. This section is proving to be quite difficult for me: When a block-level or inline-level replaced element h ...

Struggling to locate desired href links using BeautifulSoup

I'm currently working on compiling a list of hrefs from the Netflix job portal: . Each job posting on this platform comes with an anchor and a specific class: <a class=css-2y5mtm essqqm81>. To ensure accuracy, here is the complete anchor: <a ...

What are some ways to eliminate the excess white space beneath the footer in HTML?

After creating a responsive webpage that works flawlessly on mobile devices and tablets, I noticed a problem with the footer when viewed on desktop. There is an empty white space at the end of the webpage, and upon inspecting the browser, it focuses on the ...

Using a variable as a key for a JavaScript object literal with a string value

Is there a way to achieve this? objPrefix = btn.attr('data-objprefix'); //<button data-objPrefix="foo"> var sendData = {objPrefix : {"bar":"ccccc"}}; My desired outcome is {"foo" : {"bar":"ccccc"}}; however, the current result shows { ...

Refreshing the page in Next.js causes issues with the CSS classNames

I am currently in the process of migrating a React SPA to Next.js, and I am relatively new to this framework. The issue I am encountering is that when I initially load the Home page, everything appears as expected. However, if I refresh the page, incorrect ...

Identifying patterns within a string using JavaScript and TypeScript

Given a user-input pattern, for example [h][a-z][gho], and a string "gkfhxhk", I am attempting to determine if the string contains the specified pattern. The pattern dictates that the first character must be 'h', followed by any letter from a-z, ...

Avoiding duplicate clicks in Onsen UI Navigator.Avoid duplicate clicks in

When a user clicks on an item in my list, they are taken to a details page. However, if the user clicks too quickly, two click events may be fired, leading them to navigate to two different pages consecutively. Is there a way to prevent this issue? Can we ...

Having trouble with SCSS in a jsfiddle? It could be due to a pesky cross-browser bug

Can someone help me with a positioning problem I'm having? I have a span element below an image inside an li tag, but for some reason the styles are not being applied. You can check out the example in the link below: https://jsfiddle.net/ymm8xpb8/16/ ...

Is it possible to have numerous HTML files and directories in Phonegap/Cordova along with plugins?

As I transform my web app from HTML to Cordova for enhanced device functionality, including background audio and other features, I'm encountering some challenges. Due to the original structure of my application, which consists of multiple HTML files, ...

How to disable scrolling for React components with CSS styling

When incorporating a React component into my HTML, I follow this pattern: <html> <body> <div id=app>${appHtml}</div> <script src="/bundle.js"></script> </body> </html> Within my application, th ...