Tips for retrieving the ID value of the <li> element using JavaScript and AJAX

Here is a snippet of code I've been using to send the value of an <option>:

function getXhr() {
    var xhr = null; 
    if(window.XMLHttpRequest) // Firefox et autres
        xhr = new XMLHttpRequest(); 
    else if(window.ActiveXObject){ // Internet Explorer 
        try {
            xhr = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
    } else { // XMLHttpRequest non supporté par le navigateur 
        alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest..."); 
        xhr = false; 
    } 
    return xhr;
}

function go() {
    var xhr = getXhr();
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4 && xhr.status == 200) {
            leselect = xhr.responseText;
            document.getElementById('modelecontainer').innerHTML = leselect;
        }
    }

    // Here we are working on how to do a post request
    xhr.open("POST","contenu_a_charger.php",true);

    xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

    sel = document.getElementById('vehicule');
    idmarque = sel.options[sel.selectedIndex].value;
    xhr.send("idMarque="+idmarque);
}

Now, I'm looking to modify the sel variable in my existing code to obtain the ID value of an <li>.

This is what my <li> element looks like (generated dynamically through PHP):

<li id="7" onclick="go()">
    <span class="badge"><?php echo $FM->etat_user;?></span>
    <span class="head"><?php echo $FM->login_user;?></span>
</li>

And here is my old working select element:

<select name="vehicule" id="pays" onchange="go()">
    <option value="0">Select your test</option>
    <option value="3">test3</option>
    <option value="1">test1</option>
    <option value="2">test2</option>
</select>

How can I retrieve the ID value of the li element ("7" in this example)?

Answer №1

Given that you are utilizing jQuery (as indicated by the tags in your question),
You can simplify all of your code to this:

$("#7").click(function() {
    $.post("contenu_a_charger.php", "idMarque=" + $(this).attr("id"), function(returnedData) {
        $("#modelecontainer").text(returnedData);
    });
});

This approach eliminates the need for dealing with XHR objects or browser compatibility issues. Everything is seamlessly integrated within the jQuery library. It also eliminates the necessity of adding event markup directly into your HTML, allowing you to remove the onclick="go()" attribute.

Additional Note: When attaching a handler to a JavaScript event via JavaScript itself, you can simply use this inside the handler to access the event.srcElement.
(For instance, utilize this.id to obtain the value of 7)
As an illustration:

document.getElementById("7").onclick = function() { alert(this.id); }

Answer №2

Revamp the following lines:

carSel = document.getElementById('vehicle');
brandId = carSel.options[carSel.selectedIndex].value;

to be:

brandId = this.options[this.selectedIndex].value

Answer №3

For a simple vanilla JavaScript solution, you can use the following approach: If you modify your list element opening tag to

<li id="7" onclick="go(event)">
, then you can easily retrieve the id within the go function like this:

function go(event){
    var id = event.target.id || event.target.parentNode.id;
}

Note: Keep in mind that this method may not work if you have nested elements (unlike Anders' solution). However, assuming you always assign an ID to your list element, you could simplify it by doing the following:

<li id="7" onclick="go(7)">
  <span class="badge"><?php echo $FM->etat_user;?></span>
  <span class="head"><?php echo $FM->login_user;?></span>
</li>

Then you can access the ID as a parameter in your function:

function go(id){
    var xhr = getXhr();
    // ....
}

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 It Best to Override Behavior in a Directive?

Having two directives that display lists of documents, one for user-favorited documents and the other for user-pinned documents. The criteria for displaying these documents depend on the values of "pinned" and "favorite" within each document object: docum ...

What is the best way to combine a JSON response object with the variable J inside a for loop?

Received a JSON response as follows: { "name" : "chanchal", "login3" : "1534165718", "login7" : "1534168971", "login6" : "1534168506", "login5" : "1534166215", "login9" : "1534170027", "login2" : "1534148039", "lastname" : "khandelwal", ...

Ways to use the v-if directive to render conditionally based on a property, even if the object may be undefined

Keep in mind that the parent variable is a firebase reference that has already been defined. Using it like this works fine: v-if="parent['key'] == foo" However, when trying to access a child element like this: v-if="parent['key'].ch ...

What is the best way to add uppercase letters exclusively?

Is there a way to dynamically style uppercase text within an <h2> tag that is generated based on an image's alt text? I'm thinking of using javascript / jquery to identify the uppercase text and encase it in a <strong> tag, then appl ...

The styles of a jQuery Mobile listview aren't updating properly when the list items are emptied and then dynamically re-created

When I have a listview that dynamically creates its list items using JavaScript code, everything works perfectly the first time the code runs. However, upon subsequent executions, the list is generated correctly but loses the jQuery Mobile styling. Despite ...

jQuery Ajax form submission encountering issues

I created a form dynamically with the help of jQuery. Here is the code: <form id="editorform" accept-charset="utf-8" method="post" name="editorform" action="menuupdate"> <div> <input id="updateItem" type="submit" value="Update"& ...

Is it possible to convert a string of elements in JavaScript into JSON format?

Within my JavaScript code, a variable holds the following information: url=http://localhost quality=100 tag="4.4, 5.5" I am interested in converting this data to JSON format using JavaScript, like this: "result": { "url": "http://localhost", "qu ...

Frames of Animation

Seeking assistance in understanding how to create frame animation using JavaScript or CSS. Attempting to replicate the animation seen on this website. Intrigued by the road animation and unsure if it is achieved using a plugin or just JavaScript and CSS. ...

Sending data back and forth across 2 tabs within one page

I noticed a strange behavior when using multiple tabs on the same page in different modes. When I clicked a button that was supposed to fill in some inputs, the data filled in the last tab opened instead of the one I actually clicked on. The angular input: ...

How should I integrate my JS authentication function in Rshiny to enable the app to utilize the outcome?

Currently, I have an Rshiny application set to be published on the server but in order to ensure that a specific user has access, we require an API authentication token. The process of authentication is handled within JS tags outside of the application, wh ...

What is the best way to set a checkbox to null instead of false using Angular?

I am currently developing a filtering system that allows users to select different parameters to filter through a list of items. For instance, the item list could be a collection of dishes with filters represented as checkboxes labeled as vegan, vegetaria ...

Is the mounted hook not being triggered in a Nuxt component when deploying in production (full static mode)?

I have a component that is embedded within a page in my Nuxt project. This particular component contains the following lifecycle hooks: <script> export default { name: 'MyComponent', created() { alert('hello there!') }, ...

Instructions on how to implement a readmore button for texts that exceed a specific character length

I am attempting to display a "Read more" button if the length of a comment exceeds 80 characters. This is how I am checking it: <tr repeat.for="m of comments"> <td if.bind="showLess">${m.comment.length < 80 ? m.comment : ...

Moving Rows Between AgGrids

Experimenting with the example provided in this link (Dragging Multiple Records Between Grids) within my React application: https://www.ag-grid.com/react-data-grid/row-dragging-to-grid/ I have some inquiries; How can I retrieve the selected rows for the ...

The specified anti-forgery form field named "__RequestVerificationToken" is not found

Dealing with cross-site attacks is a priority for my site. Currently, I am working on developing a Master/Detail form using asp.net mvc 5 and making Ajax requests. To create a new entry, I have to follow a process involving an Ajax Request like this: $.aj ...

Locate the nearest date (using JavaScript)

Searching for the nearest date from an XML file. <?xml version="1.0" encoding="UTF-8"?> <schedule> <layout fromdt="2014-01-01 00:00:00" todt="2014-01-01 05:30:00"/> <layout fromdt="2014-02-01 00:00:00" todt="2014-01-01 05 ...

Blend jQuery fade in

I have two variables var $aa = $('#Adiv').find('li').has('class'); var $bb = $('#Bdiv'); Both variables should be faded in using fadeIn() $aa.fadeIn(); $bb.fadeIn(); If they have the same action, is it possible ...

Retrieve the link's "href" attribute and its text if they match the specified text

Is there a way to extract the href link and text from a specific type of link? <a href="google.com">boom</a> I am looking to retrieve only the 'google.com' part and the text 'boom' Furthermore, how can I filter out other ...

Order of tabs, dialog, and forms customization using Jquery UI

I'm currently working on a jquery dialog that contains a form split into multiple tabs. In order to enhance keyboard navigation, I am looking for a way to make the tab key move from the last element of one tab to the first element of the next tab. Cur ...

Struggling to figure out how to make Bootstrap toast close or autohide properly

Looking to integrate Bootstrap 5 toasts into my ASP.NET web application, I have the code below. HTML <div class="row"> <div class="toast" id="companyUpdOK" name="compa ...