1

The array data from the server is received through ajax and the buttons are created dynamically. How can I get the particular data for respective button when it is clicked. For instance: if data from server is ['a', 'b', 'c'], there are 3 buttons. When the 1st btn is clicked, it should pass 'a' in the click function and so on.

$.ajax({
    url: urltest,
    method: 'POST',
    data: data,
    success: function (response) {
        var data = $.parseJSON(response);
        $("#multiple_search_table").find("tr:gt(0)").remove();

        $.each(data, function (index, value) { // how can I pass this individual value when the button is clicked.
            $('#multiple_search_table').append('<tr><td>\n' + 
            '<button class="search-value" data-dismiss="modal"> Select</button>\n' + '</td></tr>');
        });
    },
});

How to get the respective data value in this function?

$(document).on('click', '.search-value', function () {
    //how can I get the data for specific button?
});

Thanks in advance.

0

2 Answers 2

1

You can add another data attribute to the button element. Then you can access that data attribute on clicking the button.

Demo:

var data = ['a', 'b', 'c'];
$.each(data, function (index, value) { // how can I pass this individual value when the button is clicked.
    $('#multiple_search_table').append('<tr><td>\n' + 
    '<button class="search-value" data-dismiss="modal" data-value="'+value+'"> Select</button>\n' + '</td></tr>');
});

$(document).on('click', '.search-value', function () {
    //how can I get the data for specific button?
    console.log($(this).data('value'))
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="multiple_search_table"></div>

Update: Storing the object in the data-value attribute in the form of string and access each property by the key name:

var data = [{id:1, name:"a"}, {id:2, name: "b"}, {id:3, name: "c"}]
$.each(data, function (index, value) { // how can I pass this individual value when the button is clicked.
    $('#multiple_search_table').append('<tr><td>\n' + 
    '<button class="search-value" data-dismiss="modal" data-value='+JSON.stringify(value)+'> Select</button>\n' + '</td></tr>');
});

$(document).on('click', '.search-value', function () {
    //how can I get the data for specific button?
    var obj = $(this).data('value');
    console.log('id:', obj.id);
    console.log('name:', obj.name);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="multiple_search_table"></div>

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you. it works but there's still small issue. my data is [{id:1, name:"a"}, {id:2, name: "b"}]. The log gives [object object], now how can I access id and name? var data = $(this).data('value'); console.log(data.name) it gives undefined err. I've tried JSON.stringify and JSON.parse but doesn't work.
@AmritaStha, do you want to store only the name in the data-value or the whole object? If only the name then use data-value="'+value.name+'";
@AmritaStha, added another answer by storing the object, later accessing each property on click. please check:)
Hi, why doesn't it work if there is space in the name eg: name: "Amrita Stha".
Thank you so much @Mamum. For the white spaces I changed single quote to double quotes and it worked. "<button class='search-value' data-value='"+JSON.stringify(value)+"'>Select</button>\n" .
1

You could use the data-* attribute:

$.ajax({
  url: urltest,
  method: 'POST',
  data: data,
  success: function(response) {
    var data = $.parseJSON(response);
    $("#multiple_search_table").find("tr:gt(0)").remove();
    $.each(data, function(index, value) { // how can I pass this individual value when the button is clicked.
      $('#multiple_search_table').append(`
        <tr>
          <td>
            <button data-value="${value}" type="button" class="search-value" data-dismiss="modal"> Select</button>
          </td>
        </tr>
      `);
    });
  },
});


$(document).on('click', '.search-value', function() {
  const value = $(this).data("value");
  console.log(value);
});

And PS: don't use .append() inside loops for performance reasons. Append only once after the loop:

$.ajax({
  url: urltest,
  method: 'POST',
  data: data,
  success: function(response) {
    const TRs = $.parseJSON(response).reduce((ar, item) => {
      ar.push($("<tr>", {
        append: `<td><button data-value="${value}" type="button" class="search-value" data-dismiss="modal"> Select</button></td>`
      }));
      return ar;
    }, []);
    $('#multiple_search_table').append(TRs);
  },
});


$(document).on('click', '.search-value', function() {
  const value = $(this).data("value");
  console.log(value);
});

1 Comment

I'll use append after the loop. Thank you Roko. But data-value="${value}" it didn't work for me. Instead this worked- data-value='"+JSON.stringify(value)+"'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.