Search code examples
javascriptformspaypalpaypal-subscriptions

How can I get quantity variable from user when subnmitting a form using JavaScript?


It's a PayPal Subscription Plan and unlike their old subscription plans that were HTML forms, these are JavaScript only.

The plan is set up with different pricing depending on quantity ordered, but PayPal doesn't give you any way of getting the user to submit quantity and just defaults to a quantity of 1. I can manually set the quantity in the script (shown below with quantity of 4) which works just fine but there's no point in having this sort of button if I need a different button for each quantity.

Here is the PayPal code with identifiers removed;

<div id="paypal-button-container"></div>
<script src="https://www.paypal.com/sdk/js?client-id=ABCD-ABC_1234ABCD&vault=true&intent=subscription" data-sdk-integration-source="button-factory"></script>
<script>
  paypal.Buttons({
      style: {
          shape: 'rect',
          color: 'gold',
          layout: 'vertical',
          label: 'subscribe'
      },
      createSubscription: function(data, actions) {
        return actions.subscription.create({
          'plan_id': 'P-123456789'
          'quantity': '4'
        });
      },
      onApprove: function(data, actions) {
        alert(data.subscriptionID);
      }
  }).render('#paypal-button-container');
</script>

So what I need is a way to have the actual quantity dynamically updated by the user before they hit the Subscribe button. I assume this is possible via JS but I have no idea how. The same question has been asked twice on the PayPal Community Website but no answers have yet been posted.


Solution

  • Create an HTML input or select dropdown that allows selecting the quantity. Simple example:

    <span>Qty: </span><input id="myQuantity" type="text" />
    

    ....

          createSubscription: function(data, actions) {
            return actions.subscription.create({
              'plan_id': 'P-123456789'
              'quantity': document.getElementById('myQuantity').value
            });
          },