6

I currently have a list of items with a Paypal button associated with each of them. Each item will be purchased separately by clicking on its associated button.

<ul>
    <li data-id="1">Item 1 <div class="paypal-button"></div></li>
    <li data-id="2">Item 2 <div class="paypal-button"></div></li>
    <li data-id="3">Item 3 <div class="paypal-button"></div></li>
</ul>

<script src="https://www.paypalobjects.com/api/checkout.js"></script>

<script>
    paypal.Button.render({
        // options
    }, '.paypal-button');
</script>

Unfortunately, it seems that paypal.Button.render() will only render the first element that it finds.

Is it possible to do this call on multiple elements?

Mikey
  • 6,728
  • 4
  • 22
  • 45

2 Answers2

11

You need to give each element a unique id, then call render multiple times:

<ul>
    <li data-id="1">Item 1 <div id="button-1"></div></li>
    <li data-id="2">Item 2 <div id="button-2"></div></li>
    <li data-id="3">Item 3 <div id="button-3"></div></li>
</ul>

<script src="https://www.paypalobjects.com/api/checkout.js"></script>

<script>
    [ '#button-1', '#button-2', '#button-3' ].forEach(function(selector) {
        paypal.Button.render({
            // options
        }, selector);
    });
</script>
bluepnume
  • 16,460
  • 8
  • 38
  • 48
7

If you don't like keeping track of IDs like me, you can use classes instead. And use data attributes to differentiate.

<div class="paypal-button" data-my-attribute="tree"></div>
<div class="paypal-button" data-my-attribute="dog"></div>
<div class="paypal-button" data-my-attribute="car"></div>

<script src="https://www.paypalobjects.com/api/checkout.js"></script>

<script>
    document.querySelectorAll('.paypal-button').forEach(function(selector) {
        paypal.Button.render({
            // options
            console.log( selector.dataset.myAttribute );
        }, selector);
    });
</script>
bramchi
  • 612
  • 11
  • 14
  • is `selector` a variable at the end of `paypal.Button.render`? – Kim Carlo Jan 22 '18 at 19:11
  • Indeed, it is a variable that holds the element that gets passed from the wrapping forEach loop. [Check the docs about forEach](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach). – bramchi Jan 23 '18 at 20:17
  • I'm getting an error after trying this.. it says, `Uncaught Error: Document is ready and element [object Object] does not exist`.. any ideas? – Kim Carlo Jan 24 '18 at 02:19
  • Can you share a reduced test case on [codepen.io](https://codepen.io)? Then I'd be happy to take a look. – bramchi Jan 25 '18 at 11:35
  • You are a savior. – Vibhor Dube Oct 23 '20 at 12:23