Tips for dynamically populating a dropdown menu in Laravel with Ajax and JQuery

Hey pals, I'm encountering an issue with Ajax. Everything seems to be running smoothly when the page initially loads. However, once I hit the add button to insert a new row for a second entry, things start to go haywire. The functionality is perfect upon page load, but issues arise after clicking the Add Button. Subsequently, duplicated text appears in the dropdown box

Below is my code:


$(document).ready(function(){        
    var experienceCount = 1;       
    experience_field(experienceCount);
    
    function experience_field(number){
        html = '<div class="row">';
        //rest of code...
    }

    $(document).on('click', '#experienceAdd', function(){
        experienceCount++;        
        experience_field(experienceCount);
    });

    $(document).on('click', '.experienceRemove', function(){
        experienceCount--;
        $(this).closest(".row").remove();
    });                                           
});

Please review the images provided - the first image indicates proper function upon page load with data populating in the dropdown list as expected. However, upon clicking the add button to introduce additional dynamic fields, the Ajax fails to work and adds data only to the initial dropdown list instead of subsequent dropdown lists. I am seeking a solution where the data can be added to all dropdown lists without duplication, unlike what is currently observed in the images.

Answer №1

After some troubleshooting, I realized my mistake - I had been using the ID instead of the Class name

$.ajax({
  url: "{{ route('previousHospital') }}",
  method:'get',
  data:$(this).serialize(),
  dataType:'json',                
  success:function(data)                  
  {                       
    $('.PreviousHospital').find('option').remove();                             
    $(".PreviousHospital").append('<option selected="selected">Select Previous Hospital</option>');
    $.each(data, function(value, text){                     
      $(".PreviousHospital").append('<option value="' + text.Hospital + '">' + text.Hospital + '</option>');
    });                      
  }                  
});

Answer №2

Insert this code before each append:

$('#PreviousHospital').find('option').remove();

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

Is there a way to showcase time through ApexCharts?

I have been exploring the capabilities of ApexCharts to present data using a timeline chart. The example in Vue just illustrates how to display dates like: new Date(1797, 2, 4).getTime(), new Date(1801, 2, 4).getTime() However, I am curious about how to c ...

Anticipated a JavaScript module script, but the server returned a MIME type of text/html as well as text/css. No frameworks used, just pure JavaScript

I have been attempting to implement the color-calendar plugin by following their tutorial closely. I have replicated the code from both the DEMO and documentation, shown below: // js/calendar.js import Calendar from '../node_modules/color-calendar&ap ...

jQuery radio button for mobile devices

I'm currently working on a web application using jQuery 1.9.1 and jQuery Mobile 1.3.2. One issue I'm facing involves horizontal radio buttons that display an icon: data-icon="radio-on". These radio buttons are dynamically added to the DOM. Her ...

Delineating the execution of a PHP function through a button click using HTML/Javascript

I have a need to trigger a specific PHP function by simply clicking on a button. Currently, I am working with the following code snippet: <table class='standardtable'> <tr> <th>Event</th> <th>Group</th> ...

Learn the process of adding values to HTML forms within ExpressJS

I am facing a challenge in injecting Javascript variable values into HTML forms on an Expression JS server. I am unsure about how to solve this issue. All I want to do is insert the values of x, y, and res into the forms with the IDs 'firstvalue&apos ...

Utilizing the Google Geocode API to handle a promise with a substantial array

My Objective To efficiently process a large array using the .map method and interact with the Google Geocoder API through promises to get location data. The goal is to utilize Promise.all to store results in a .json file upon completion of the operation. ...

The JavaScript function on the specified /url page is not functioning properly following the execution of history.push(/url) on click

I have a JavaScript function that toggles the display of login password. However, when I redirect to the login page from another page using history.push(/login), the function does not work. It does work when I use (/login) in the href tag. How can I resolv ...

Utilizing a jQuery plugin called FullCalendar, dynamically create and set events using a

Using the jQuery full calendar, I am looking to dynamically set events. Here are some examples of events I need to set: events: [ { title: 'Long Event', start: '2016-09-07', ...

Unlocking a chain reaction with Ajax in JSF2

Is there a way to achieve a domino effect when rendering various panelGroups using JSF2 and Ajax? The idea is that depending on the result, a specific panel will be rendered and displayed, which in turn triggers the rendering of another panel. Is it possib ...

Bing Translator and XMLHttpRequest are two powerful tools for translating and

When running the code snippet below, I encounter an issue where I am not receiving status 200 and responseText. However, when using the following URL: http://api.microsofttranslator.com/V2/Http.svc/GetLanguagesForTranslate?appId=F1B50AB0743B541AA8C070890 ...

Beware of potential infinite update loops when using a basic toggle function in Vue.js

I have been researching the issue of infinite update loops, but I am still struggling to grasp the concept. Despite my efforts, I keep encountering the following error message: [Vue warn]: You may have an infinite update loop in a component render functi ...

Making a node.js API call using multipart/form-data

Submitting Data Using POST https://i.sstatic.net/iVTDd.png Node.js Data Capture Method without the Use of Express and Body-Parser FORM DATA: ORDERID: MID: TXNID: TXNAMOUNT: 5.00 PAYMENTMODE: NB CURRENCY: INR TXNDATE: 2021-06-14+23%3A02%3A30.0 STATUS: ...

Invoke a function within one component using another component

I am facing an issue with deleting playlists displayed on my page. These playlists are fetched from an external API and each playlist has a delete button which is supposed to remove the playlist both from the API and the view. The deletion process works s ...

Is there a jQuery function that can produce repeated output and append content with each successive click?

Attempting to implement a dynamic searchbar with various parameters has led me to explore using jQuery to load and clone the searchbar file in order to append it to the body dynamically. I have made several attempts to modify selectors without achieving t ...

The Bootstrap modal causes the scrollbar to vanish upon closure

Despite trying numerous solutions and hacks on this issue from StackOverflow, none of them seem to work for me. Currently, I am utilizing a modal for the login process in Meteor (e.g. using Facebook login service) which triggers a callback upon successful ...

Is it possible for Nuxtjs/apollo to make apollo wait for other requests before initiating the query?

Is there a way to have Apollo wait for the result of one request to a third party before making either of two queries? Or should I manually add the appropriate query to Apollo after receiving the results? ...

The readStream in Node.JS unexpectedly terminates before the writeStream

I'm currently working on a project that involves fetching PDF files from remote servers and immediately sending them back to the clients who made the request. Here is the code snippet I am using: var writeStream = fs.createWriteStream(filename); writ ...

Uploading files through AJAX modal window (elevate)

Is there a way to successfully upload files within an AJAX modal window in Lift? I attempted the following approach: ajaxForm( bind("upload", template, "file" -> SHtml.fileUpload(processFile _), "submit" -> SHtml.ajaxSubmit("Subm ...

Utilizing HTTP PUT for transmitting JSON data via Jquery in Rails 3

HTTP PUT may not work across all browsers, so in Rails (specifically Rails 3), you can use POST and pass the _method query parameter instead. However, this method does not seem to be effective when sending JSON data. For example: $.ajax({ url: window ...

Corporate firewall causing issues with AJAX call execution

Currently, I am utilizing jQuery's $.ajax() method to retrieve approximately 26KB of JSONP data. All major browsers including FF, Chrome, IE, and Safari are successfully returning the data from various locations such as work, home, and mobile phone w ...