Aryayan Roy
Aryayan Roy

Reputation: 15

How to use buttons with different Values but same ID for jQuery?

I have a table which generated by PHP and MySql. One of the column will have buttons which will have values which will be used for sending a data to another PHP file using AJAX. But I am now facing a problem that id(s) can have only unique value.

Will it be possible to use same ID for buttons with different values.

Here is a dummy data of HTML (Output given by PHP).

<table>

<tr>
<th>Serial No.</th><th>File Name</th><th>Action</th>
</tr>

<tr>
<td>1</td><td>Physics Notes</td><td><button id="request" value="1">Download</button></td>
<tr>

<tr>
<td>2</td><td>Chemistry Notes</td><td><button id="request" value="2">Download</button></td>
<tr>

<tr>
<td>3</td><td>Mathematics Notes</td><td><button id="request" value="3">Download</button></td>
<tr>

</table>

Now I want when any of the buttons in the 3rd columns are clicked, their values to be receive in the jQuery variable "file". And then the values will be sent to a PHP file via AJAX.

Here is my jQuery and AJAX code.

<script src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("#request").on("click",function(e){
    e.preventDefault();
    var file = $(this).val();
    $.ajax({
      url : "downloadfile.php",
      type : "POST",
      data : {file:file},
      success : function(data){
        alert("Thank you for using our service");
      }
    });
  })
});
</script>

Upvotes: 0

Views: 490

Answers (1)

As said in Comment, an ID shall always be unique. So use class in your case.

<td><button class="request" value="2">Download</button></td>

and

$(".request").on("click", function(e) {

Note Please note that you haven't closed your tr they are missing /

Demo

$(document).ready(function() {
  $(".request").on("click", function(e) {
    e.preventDefault();
    var file = $(this).val();
    $.ajax({
      url: "downloadfile.php",
      type: "POST",
      data: {
        file: file
      },
      success: function(data) {
        alert("Thank you for using our service");
      }
    });
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>

  <tr>
    <th>Serial No.</th>
    <th>File Name</th>
    <th>Action</th>
  </tr>

  <tr>
    <td>1</td>
    <td>Physics Notes</td>
    <td><button class="request" value="1">Download</button></td>
  </tr>

  <tr>
    <td>2</td>
    <td>Chemistry Notes</td>
    <td><button class="request" value="2">Download</button></td>
  </tr>

  <tr>
    <td>3</td>
    <td>Mathematics Notes</td>
    <td><button class="request" value="3">Download</button></td>
  </tr>

</table>

Upvotes: 1

Related Questions