Use radio buttons to enable switching between different data options within a dropdown menu

I am working on a dropdown box that is populated dynamically using JSON data. The content in the dropdown can be categorized into 4 types, so I have included radio buttons to switch between these categories.

I have created HTML code to toggle between manually entered data in the dropdown, but I am unsure about how to achieve the same functionality for dynamically generated data.

Below is the current code snippet. Any help or suggestions are greatly appreciated.

<script>
var listA = [{name:'ALM_1', value:'ALM_1'}, {name:'ALM_2', value:'ALM_2'}, {name:'ALM_3', value:'ALM_3'}];

var listB = [{name:'BR_1', value:'BR_1'}, {name:'BR_2', value:'BR_2'}, {name:'BR_3', value:'BR_3'}];

var listC = [{name:'BUG_1', value:'BUG_1'}, {name:'BUG_2', value:'BUG_2'}, {name:'BUG_3', value:'BUG_3'}];

var listD = [{name:'Feat_1', value:'Feat_1'}, {name:'Feat_2', value:'Feat_2'}, {name:'Feat_3', value:'Feat_3'}];

$(document).ready( function() {
  $("input[name='chk']").on('change',function() {

      if($(this).is(':checked') && $(this).val() == 'ALM')
      {
        $('#describe').empty()
        $.each(listA, function(index, value) {
         $('#describe').append('<option value="'+value.value+'">'+value.name+'</option>');
        });                  
      }
      else if($(this).is(':checked') && $(this).val() == 'BR')
      {
        $('#describe').empty()
        $.each(listB, function(index, value) {
         $('#describe').append('<option value="'+value.value+'">'+value.name+'</option>');
        }); 
      }
      else if($(this).is(':checked') && $(this).val() == 'BUG')
      {
        $('#describe').empty()
        $.each(listC, function(index, value) {
         $('#describe').append('<option value="'+value.value+'">'+value.name+'</option>');
        }); 
      }
       else if($(this).is(':checked') && $(this).val() == 'FEAT')
      {
        $('#describe').empty()
        $.each(listD, function(index, value) {
         $('#describe').append('<option value="'+value.value+'">'+value.name+'</option>');
        }); 
      }

  });
});  

Answer №1

I'm a bit confused about how to manage data that's being generated dynamically.

When working with dynamically generated data, it's important to use event delegation like this:

$("body").on('click', 'button[name="btn"]', function() {
    //Add your code here
})

I hope this explanation is beneficial to you.

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 the best way to categorize an array based on a specific key, while also compiling distinct property values into a list

Suppose there is an array containing objects of type User[]: type User = { id: string; name: string; role: string; }; There may be several users in this array with the same id but different role (for example, admin or editor). The goal is to conv ...

Customize the HTML tags in the Froala text editor with easy insertion and removal

In my AngularJS project, I am utilizing Froala editor. I want to create a unique functionality where a custom button wraps selected text with <close></close> tags when activated. Moreover, if the selected text is already wrapped with these tags ...

How can we use jQuery to replace a u002D in a string obtained from an attribute

My goal is to extract the URL inside the "ng-init" attribute from this particular div element. <div ng-controller="CloudcastHeaderCtrl" ng-init="juno.replaceTracklist=true;juno.guid='DBFFF66E\u002D4111\u002D446B\u002D8471\u002D ...

Add a fresh listing arranged alphabetically using either JavaScript or jQuery

I currently have a set of lists that are already alphabetically sorted. For example: <ul> <li><a href='#'>Apple</a></li> <li><a href='#'>Banana</a></li> <li><a href=& ...

What is the best way to position this container in the center of the

Is there a way to perfectly center this container both vertically and horizontally? I've attempted the method below without success. Unsure of what is missing: HTML: <div class="box"> <p>This is a sentence.</p> </div> C ...

When I select an option with an object, ng-model is receiving '[object Object]' instead of the actual object for <select> element

Referencing an example from Angular documentation: this link, specifically the section on "Using ngValue to bind the model to an array of objects." In the index.html file: <!doctype html> <html lang="en"> <head> <meta charset="UTF- ...

Display a standard chart using the Chart.js library, along with customizable options

I have successfully generated charts from a database using JSON script. However, I am facing an issue where the chart only displays when I click on an option value. What I want to achieve now is setting a default value option so that when the website ope ...

What is the best way to make a Modal triggered by a loop embedded within a table function properly on mobile devices?

While the modal is functioning properly on desktop, it seems to be encountering issues on mobile devices. The modal appears behind the background and is confined by the boundaries of the table (tbody). Below is the code snippet for triggering the modal: ...

Is it conceivable that Rails may be rendering HTML at a slower rate compared to static

When using a Rails layout, you can include HTML tags to render images like this: <%= image_tag("logo.png", :alt => "Sample App", :class => "round") %> This will generate the following HTML code: <img alt="Sample App" class="round" src="/i ...

The use of ReactDom.render is no longer permissible in Next.js

I just set up a fresh Next JS application using Next 12. Encountering this issue consistently on every page load in the browser: Alert: The use of ReactDOM.render is no longer supported in React 18. Please switch to createRoot instead. Until you make th ...

What is the best way to display HTML content inside a pop-over window?

How can I load popover content from another HTML file using templateUrl in AngularJS? Check out the demo below: HTML: <!DOCTYPE html> <html ng-app="plunker"> <head> <meta charset="utf-8"/> <title>AngularJS Plunker& ...

The backbone view is having trouble processing the data from this.model.toJSON()

I've been working on a Backbone code implementation to display all modifications before adding data to my model. However, every time I try to add something from my form, my view returns "this.model.toJSON() is not a function" and I can't figure o ...

Troubleshooting: Next.js - Issues with encodeURIComponent function when using `/` in getStaticPaths

Reproducible site showcasing the issue: Reproducible code example: https://github.com/saadq/nextjs-encoding-issue Homepage Food page The goal is to dynamically create static pages for different food items based on their titles. This functionality works ...

Initiating actions upon the 'onload' event in AJAX response data

My friend and I have been exploring a website that has a button triggering an AJAX call. The call loads HTML into a specific DIV tag and runs a Javascript function upon successful return. However, we've encountered an issue where the button only works ...

Is it possible for an object to receive notifications when a component object undergoes changes in Angular 2/4?

When working with Angular components, it's possible to pass a variable or object as @Input(). The component will be notified whenever the value of this input changes, which is pretty cool... I'm currently developing an application that features ...

When changing the dropdown option on a separate page in React/Next JS, all checkboxes show the clicked style as a result of utilizing useState

I have implemented checkboxes for three different categories: "Types", "Price", and "Categories". They function correctly, with data being passed to a separate checkbox component without any issues. The problem arises when I click a checkbox and then inte ...

What is the best way to structure the layout: Subdomains or External CSS for Web and Mobile Web?

I'm currently working on designing an application that needs to be compatible with both web and mobile web browsers. Due to the differences in screen sizes, I understand that I will need to create different layouts and views to ensure optimal user exp ...

Firebase issue: The function ref.once is throwing an Uncaught TypeError and is not recognized

I am attempting to utilize Firebase for both uploading a file and storing it in my database simultaneously. I want to track the number of uploads so that I can rename each file uniquely. While I have successfully uploaded and stored a copy in the database, ...

What steps do I need to take to incorporate Material UI icons into my REACT project?

After reviewing the documentation, I found it somewhat confusing with terms such as "MaterialIcon, SVGIcons, Icons". If you are interested, you can check out the link here. I am looking for a simple explanation of the process from installation to using th ...

Live Update Google Sheet Data to JSON Without Reloading Web Page

This particular function is executing smoothly. My main concern lies in updating a DOM element without reloading the webpage, if any alterations are made to the data on a Google sheet I am utilizing a JSON file from Google sheets: https://spreadsheets.g ...