Create copy link button in list with unique value - PHP and JavaScript
P粉211273535
P粉211273535 2023-09-16 00:15:27
0
1
567

I'm writing my own WordPress plugin, which is why some of the code might look a little weird. But my problem is with plain old PHP.

I created a list of players, each player has a unique URL. I want to have a "Copy Link" button on each row/player. But I can't seem to get this to work.

I don't want to update the site on copy, so I guess I need to use something like Ajax. But I have no experience.

I tried creating it using JavaScript but when I pass in the link (string) it keeps printing an error. It prints: "Unexpected token ':'. Expected ')' to end parameter list."

I have set up my PHP file like this:

<?php
// Fetching the players //

foreach($players as $player) {
    $player_email = get_post_meta($player->ID, 'email')[0];
    $player_status = get_post_meta($player->ID, 'status')[0];
    $player_link = get_permalink($player->ID);
    
    if ($player_status == 'Not completed') { array_push($not_completed_players, 'true'); }
    $return_html .= '
    <li class="players-div">
      <div class="players-text-div"> 
        <p class="players-list-p players-name"> ' . $player->post_title . ' </p>
        <p class="players-list-p players-email"> ' . $player_email . ' </p>
      </div>

      <a class="players-list-p" href="' . $player_link . '"> /' . basename($player_link) . ' </a>
      <p class="players-list-p players-email"> ' . $player_status . ' </p>

      <button type="button" onClick="copyToClipboard(' . $player_link . ')" name="copied_link" value="' . $player_link . '"> Copy link </button>
    </li>';
 }

?>

<script>
  function copyToClipboard(playerLink) {
    navigator.clipboard.writeText( playerLink );
  }
</script>

P粉211273535
P粉211273535

reply all(1)
P粉439804514

You should surround the parameters of the copyToClipboard function with double or single quotes. This solution escapes ' by adding a backslash (\):

copyToClipboard(\'' . $player_link . '\')

Your player link may contain https: and the colon will cause an error message.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!