ajax always returns the same value, even when the input value is different

Each time I click on a different value, the console.log keeps giving me the same value. view image description

I have checked the HTML code and found that even though each value attribute is different, it still returns the first value of the attribute. view image description

There are two options for AJAX. Here's what I've tried:

<script type="text/javascript>

    $(function(){
        $('.categoryList').click(function(){
          
          var cat_id = $(this).attr('value');
          var url = "http://localhost:8000/api/getSubcategory/"+cat_id;
          $.ajax({
              type: "GET",
              url: url,
              dataType: "JSON",
              success: function(res)
              {
                var html = "";
                $.each(res, function (key, value) {
                     html += "<option  value="+key+">"+value+" </option>";
                });
                 $('#subcategory').html($(html).addClass('subcategoryList'));

              }
          });
        });

    });
$(document).ready(function() {
    $('#subcategory').click(function() {

       var  subcat_id = $( this ).find( '.subcategoryList' ).attr('value');
          console.log(subcat_id);
          var url = "/api/getSubcategorytwo/"+subcat_id;
          $.ajax({
              type: "GET",
              url: url,
              dataType: "JSON",
              success: function(res)
              {
                
                var html = "";
                $.each(res, function (key, value) {
                     html += "<option value="+key+">"+value+"</option>";
                });
                $("#subcategorytwo").html(html);

              }
          });
        });

    });
</script>
                   <div class="col-md-4">
              
                        @foreach($categories as $category)
                        <option class="categoryList" value="{{$category->id}}">{{$category->category}}</option>
                        @endforeach
                    
                    </div>
                 
                        <div class="col-md-4">
                        <a name="subcategory" id="subcategory">
                         </a>
                        </div>
                  
                       <div class="col-md-4">
                        <a name="subcategorytwo" id="subcategorytwo">
                          <option value=""></option>
                        </a>
                        </div>
           

enter code here

Answer №1

The code provided in the html is completely incorrect. You have two options: use the <a /> anchor tag or the

<select><option></option> </select>
select tag.

If you opt for the anchor tag, you will have the click functionality, but your html file will contain a long list of anchors.

On the other hand, if you select the select tag, you can trigger the on change event and retrieve the selected value. You can utilize either of the following:

on change function

change event handler using jquery

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

Having trouble with playing the appended HTML5 Video?

Having trouble getting a video player to display after clicking a button. This is the code I use to add the video player in index.html: $("#videoContainer").append( "<video id=\"video-player\" width=\"100%\" height ...

Should the .js file type be omitted in the <script> tag for semantic accuracy?

Upon reviewing some inherited code, I noticed that JavaScript files are being linked in the following format: <script src="/js/scriptfile" type="text/javascript"></script> However, I was expecting to see: <script src="/js/scriptfile.js" ...

javascript categorize data by key and display in a tabular format

I have a Client ID and gender information available. Shown below is a JSON response along with a JavaScript function to display the data in a table format. The JSON response structure is as follows: studies = [{ "id": { "Value&qu ...

What could explain why the event listener functions properly on the initial call but fails on subsequent calls?

Currently, I am working on a bootstrap carousel where the "Previous" button is hidden on the first slide and the "Next" button is hidden on the last slide. Now, I want to disable the next button on the second slide (and eventually all slides with iframe vi ...

What could be the reason for the child element not occupying the full height of its parent container?

* { padding: 0; margin: 0; box-sizing: border-box; } body { margin: 50px; } .navbar { display: flex; align-items: center; justify-content: center; color: darkgreen; font-family: 'Vollkorn', serif; font-size: 1.2rem; font-w ...

Navigate the array and divide the elements into separate values

For a project I need to upload files, wherein the data is organized within an object like [5.76516834507, 50.8474898368], [5.76115833641, 50.8453698247]. The task here is to extract and store the first value as latitude: 5.76516834507 and the second value ...

UPDATE: Choosing several classes and then toggling the classes independently for each one

I have managed to make this work, but I am considering if there is a more efficient solution. My objective is to modify the divs using classes exclusively. I aim to toggle 4 classes with just one click. First, I obtain the class for the button and then a ...

The JQuery TextNTags plugin eliminates tag formatting once the trigger syntax has been modified

I have incorporated the JQuery TextNTags plugin into my web application. Here is the original code snippet: $.browser = { webkit: true }; $(function () { $('textarea.tagged_text').textntags({ triggers: {'!': { ...

Tips for managing Ajax JSON response in a PhoneGap application

Although there are a few posts on this topic, I am struggling to piece together the necessary components to make it work. I am in the process of converting a web application into an app using phonegap and I am attempting to create a search form that retri ...

Extracting Data from JSON Using Vue.js

I am facing an issue with extracting data from a JSON file using Vue.js. Below is the HTML and JSON data along with the script. Any help would be appreciated. <!DOCTYPE html> <html> <head> <title>Vu ...

issue with visibility of checkbox in material ui table row

In a separate file called TradesTable.js, I have created a table using Material UI for my React app. const DummyTableRow = (props) => { let myRows = props.trades.map((trade, index) => { return <TableRow> <TableRowColumn ...

Modify an array by incorporating values from another array that have a matching property

I have two arrays that look like this let array1 = [{ 'id': 1, 'name': 'A' }, { 'id': 2, 'name': 'B' }, { 'id': 3, 'name': ' ...

Getting a user's group name from Azure Active Directory in an Angular application - a step-by-step guide

I have connected to Azure directory using ng2-adal (https://github.com/mazhisai/ng2-adal-QuickStart) and successfully obtained a group id in the format: "groups":["4ba2649e-20d2-40f4-a406-2ed897686403","43e19f05-c077-4716-b001-0ffb0d75fff8"]. Is there a w ...

Using Selenium to interact with a Modal Dialog window

When trying to navigate to a page in IE9 using Selenium, a certificate error message appears on the page. By using AutoIT, I am able to click within the browser, TAB twice, and hit enter without any issues. However, after this step, an error for a "Modal d ...

Having difficulty incorporating multiple "if" statements into my code

I'm currently working on creating an IE9 specific if statement. Basically, I want to check if the menu is collapsed and then move 3 classes from the left if it is true, or in the opposite direction if it is false. However, I'm struggling to get t ...

Exploring a JavaScript function that triggers another function to create a new object - Utilizing Sinon and Mocha for testing purposes

I am currently working on a nodejs application where I need to write a test for a function that invokes another function to create a new object, and then calls a method of that object. Below is the code in service.js that I am trying to test; // servic ...

Making PanelGrid clickable with a4j:support keeps the page from refreshing after clicking

I have successfully created a button using HTMLPanelGrid and HTMLAjaxSupport (a4j:support from backing bean) that triggers an 'onclick' event. The event listener linked with the HTMLAjaxSupport appends a new component to the page, which has its ...

jQuery: Remove the class if it exists, and then assign it to a different element. The power of jQuery

Currently, I am working on a video section that is designed in an accordion style. My main goal right now is to check if a class exists when a user clicks on a specific element. The requirement for this project is to allow only one section to be open at a ...

Encountering challenges with managing global variables in my Node.js application

I am facing a problem with global variables in my NodeJs application. The project involves webservices created using the express module. When a client accesses the service, a json object is sent in the request body. I extract all properties from the reques ...

Is there a way to consistently trigger the browser.webRequest.onBeforeRequest event in Mozilla Firefox when it is launched via a link?

Hello knowledgeable individuals. I am unable to solve this issue on my own. Here is the add-on I have created: 1) manifest.json: { "manifest_version": 2, "name": "Example", "version": "1.0", "description": "Example", "permissions": [ "tabs" ...