1

I have multiple divs(containing input fiels with some unique id in each) which were created dynamically by ejs so they all contain same class name.

I want to make ajax call from only that one div's form(matching the unique id) using jquery. How can i do that?

I found lots of similar questions on google but not what i am looking for. Also before you mark this for duplicate, atleast help me with this.

This is my code:

In ejs:

<% elements.forEach(e => { %>
  <input class="uniqId" value="<%=e.id%>">
  <button type="button" class="btn">
<% }) %> //looping through all the data i have and storing unique value in input field

In the javascript/jquery part:

$('.btn').on('click', () => {
    $('input.uniqId').val();

    //and then i want to perform ajax call from that specific input field data(the one whose button i clicked)
});
Rory McCrossan
  • 306,214
  • 37
  • 269
  • 303
NameError
  • 17
  • 4
  • `$(document).on('click', '.btn', function() { var val = $(this).prev('input').val(); });` – Rory McCrossan Sep 09 '19 at 13:04
  • @RoryMcCrossan wow that works! sorry if its already asked, i am new to programming. can you provide some links/documentations to know about how siblings and parents work in jquery and javascript? Thanks again. – NameError Sep 09 '19 at 13:22
  • I'd suggest Googling for what you asked - this is the first hit which seems to be a good guide: https://medium.com/@timothyrobards/javascript-fundamentals-master-the-dom-part-2-bef36405598e – Rory McCrossan Sep 09 '19 at 13:23
  • @RoryMcCrossan thanks i'll definitely look into it. But i have a doubt about how does this work. Shouldn't it get values from all the previous dom elements of ".btn" class(all input fields) elements since there are more than one of them in the document actually? – NameError Sep 09 '19 at 13:33
  • No, as it uses `prev()` to only get the previous sibling `input` of the `button` which was clicked – Rory McCrossan Sep 09 '19 at 13:34
  • No i mean there are multiple buttons with the class:btn and hence multiple input field before each prev class button, within the whole document right? so does it mean the on() event-binder selects the dom differently than normal selectors? – NameError Sep 09 '19 at 13:40
  • Ah. Yes it does. Instead of attaching an event handler to every `.btn` element it add a single event handler to a parent element (the document in my example above) and listens for all events bubbling up through the DOM to see if they were `.btn` elements and then run the handler logic. – Rory McCrossan Sep 09 '19 at 13:44
  • ok so now it makes sense. Thanks so much for clarity. – NameError Sep 09 '19 at 16:18

0 Answers0