Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery get value from text

 <td class="left">
      <span class="copyTarget"><?php echo $coupon['code']; ?></span>
      <a class="copyButton">[Copy code]</a>
  </td> 

Here is the result:

javascript code

$('.copyButton').click(function() {
  var a = $('.copyTarget').text();
   alert(a);
});

Output results when click the button:

results output when click the button

Question: When I press the button, it will return all the value from code, for example, there are 4 value which is promo10,yesss,promo111,zz12. But what I want is when i click the copy code button , then only copy one code I want. How can i do that T.T ???

like image 234
Ch Minn Avatar asked Jul 25 '26 16:07

Ch Minn


2 Answers

You could use .closest() or .siblings() or .prev() to target the related .copyTarget span :

$(this).closest('td').find('.copyTarget').text();
//or
$(this).siblings('.copyTarget').text();
//or
$(this).prev('.copyTarget').text();

Hope this helps.

$('.copyButton').click(function() {
   console.log( $(this).siblings('.copyTarget').text() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="left">
      <span class="copyTarget">Code 1</span>
      <a class="copyButton">[Copy code]</a>
    </td>
  </tr>
  <tr>
    <td class="left">
      <span class="copyTarget">Code 2</span>
      <a class="copyButton">[Copy code]</a>
    </td>
  </tr>
  <tr>
    <td class="left">
      <span class="copyTarget">Code 3</span>
      <a class="copyButton">[Copy code]</a>
    </td>
  </tr>
</table>
like image 70
Zakaria Acharki Avatar answered Jul 28 '26 06:07

Zakaria Acharki


You can use siblings to get the element that contains the code.

$(".copyButton").on("click", function(e){
    var text = $(this).siblings(".copyTarget").text();
    alert(text);
});
like image 38
james_bond Avatar answered Jul 28 '26 06:07

james_bond



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!