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

What is causing the left scroll to not work with negative values?

My design features three blocks stacked on top of each other with an additional block at the bottom below the middle. Left <--------> Middle<---------->Right -----------------Bottom------------------ I have a couple of queries. Why is scr ...

Using Selenium and PhantomJS for web scraping to retrieve information on product details

As a beginner in web scraping with Python, I am currently working on extracting product details from a webpage using Selenium and PhantomJS. However, I am facing a challenge as the page does not display the rendered HTML when I try to access it using "driv ...

Issue with compiling Tailwindcss in nextjs JIT mode

Our current project involves using tailwindcss and things were going smoothly until the clients requested a "pixel perfect" design. This meant that every element needed to be set in pixels instead of rem units. Instead of adding countless classes like h-1p ...

When using NextJS, the dynamically generated HTML elements do not get affected by CSS repaint

Recently, I encountered an issue while working on a Next.js project involving the addition of an external script that uses vanilla JavaScript to dynamically create nodes. Despite importing global CSS at the top of my _app.js file, I noticed that the styles ...

How can I implement a scroll functionality to navigate to the next item in a Vuetify v-carousel?

I'm currently working on a front page layout using the v-carousel component and I am looking to achieve automatic scrolling to the next item without the need for arrows or delimiters. How can I make this happen? Below is my current code: <template ...

Inconsistency in date serialization using JSON.stringify across various web browsers

I've written this snippet in an HTML file: alert(JSON.stringify(new Date())); To cater to older browsers lacking JSON.stringify(), I've included the latest json2.js (2009-09-29 version) along with jquery-1.3.2.js. In modern browsers with native ...

Getting URL Parameters in Angular JS

How should one go about retrieving URL parameters in Angular? For instance, consider this URL: http://example.com/mypage.html?product=1234®ion=4&lang=en Thank you ...

What is the method for shortening the sizable text "Hereisthelargetextbreakwithphp" to "Hereisthelarge..." using PHP?

Modify the large text "Hereisthelargetextbreakwithphp" to "Hereisthelarge..." $string = "Hereisthelargetextbreakwithphp"; $string = strip_tags($string); if (strlen($string) > 21) { $stringCut = substr($string, 0, 21); echo $string = substr($str ...

The canvas animation displays a sequence of previous frames

My challenge lies in rotating an object on the canvas, as all previous frames continue to be displayed. I suspect the issue is related to this particular line of code: setTimeout(this.rotate.bind(this), 1000 / 10); Is there a way to have only the current ...

Changing the cursor to a waiting state following a mouse click

Looking for some help here - when I click a button, the cursor remains standard and doesn't show loading. Any suggestions on how to fix this? Below is the snippet of my code: <div class="signup"> <input type="submit" value="Sign Up" tit ...

.parseXML yields no results

I am struggling to interpret a response from a server that should be in XML format. While I am new to web development, I am trying to quickly grasp JavaScript for an assignment. Unfortunately, I cannot control the server. My code snippet is as follows: . ...

The inversify middleware is executed a single time

I utilize Inversify for object binding in the following manner: container.applyMiddleware(loggerMiddleware); let module = new ContainerModule((bind: interfaces.Bind) => { bind<Logger>(TYPES.Logger).toConstantValue(logger); bind<ILogger ...

Transform a JSON array with keys and values into a structured tabular format in JSON

Looking to transform the JSON data below for a Chart into a format suitable for an HTML table: var chartJson = [ { header : '2016', values : [1, 5, 9] }, { header : '2017', values : [2, 4, 8] ...

Simulated FileList for Angular 5 App Unit Testing

Imitation FileList In my pursuit of writing a unit test (Angular5), I have encountered the need for a FileList. Despite researching extensively, I have been unable to uncover any clues or solutions. I am starting to question whether this is even feasible ...

Retrieve the <style> tag response and inject it into the head section of the HTML using React

Although I am aware that this may not be the best practice, it seems to be the most suitable solution for this particular case. The server response contains something like this: <style id="styles">.color_txt{color:green;}</style> I am attempt ...

Changing the class of a div in JavaScript from one class to another

On my HTML page, I have a div with a CSS class assigned to it. The goal is to switch the current class for another when a button is clicked. It's crucial that not a single CSS property within the class is altered - the entire class must be replaced en ...

Nested within an it block are Protractor Jasmine describe blocks

Initially, the code provided below appears to be functioning properly. However, I have not come across anyone using this method before, leading me to question its validity and potential unforeseen drawbacks. The scenario involves writing an end-to-end tes ...

A comprehensive guide on implementing form array validations in Angular 8

I am currently using the formArray feature to dynamically display data in a table, which is working perfectly. However, I am facing difficulty in applying the required field validation for this table. My goal is to validate the table so that no null entry ...

Utilize React-select in Nextjs to dynamically alter URLs through options

During my attempt to implement react-select for changing the URL based on user-selected multiple options to filter numbers, I encountered a challenge. When using multiple options, the URL changes successfully to fetch data, as seen in this example: https:/ ...

Tips for dynamically displaying images in both horizontal and vertical orientations

I would like to showcase images in the imageList. Here is what I want: AB CD How can this be achieved? It's not a matter of being even or odd Perhaps the list could look something like this: ABCDE FG I simply want a new row or display:block when ...