Take only the item from the list that I just clicked and used it

I have a list, and when someone clicks on the li element and then on $ .ajax (), I get the data he needs.

for ie:

<li id="test1">test 1 </li>
<li id="test2">test 2 </li>
<li id="test3">test 3 </li>
...
<li id="testN">test N </li>

So, the ajax part is for test 1:

$('#test1').click(function() {

 $.ajax({
  url: 'fetch.php',
  type: 'POST',
  data: { temp : 'test1'},
  success: function(data) {
    $('#test1').append(data);
  }    
});

and the same for 2,3,4 ... N

But the problem is that this is too much code ... just paste the paste, but can I do it differently? value when i click the element test1 jQuery detects which element i clicked and runs for it ...

Sorry my bad english thanks

+3
source share
3 answers

Try:

<li class="test" id="test1">test 1 </li>
<li class="test" id="test2">test 2 </li>
<li class="test" id="test3">test 3 </li>
...
<li class="test" id="testN">test N </li>

and then

$('.test').click(function() {
    var $this = $(this);
    $.ajax({
         url: 'fetch.php',
         type: 'POST',
         data: { temp : $this.attr('id') },
         success: function(data) {
             $this.append(data);
        }    
    });
});
+3
source

class="test" LI $(".test") UL <ul id="tests"> LI UL $("#tests li")

+1

Use this change even to work only when you select an item from the list:

$('#test1').change(function() {
    $.ajax({
    url: 'fetch.php',
    type: 'POST',
    data: { temp : 'test1'},
    success: function(data) {
        $('#test1').append(data);
    }    
});
+1
source

Source: https://habr.com/ru/post/1780213/


All Articles