<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:

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 ???
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>
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With