Saleh Ahmad Oyon Saleh Ahmad Oyon - 7 months ago 24
Javascript Question

How can I put jQuery in <script> attribute?

I want to write jQuery in script attribute.

<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_11a6LFgOQ9rZ3d54Qd0uBF8c"
data-amount="2000"
data-name="Oyon Shop"
data-description="Thank you for puchasing!"
data-image="/img/demo.png"
data-locale="auto">




The value of data-amount will be
$('#amount').val()
. How can I do this thing?

Answer

You can actually do it using appendTo this way:

$("<script>", {
  src:"https://checkout.stripe.com/checkout.js",
  class: "stripe-button",
  "data-key": "pk_test_11a6LFgOQ9rZ3d54Qd0uBF8c",
  "data-amount": $('#amount').val(),
  "data-name": "Oyon Shop",
  "data-description": "Thank you for puchasing!",
  "data-image": "/img/demo.png",
  "data-locale": "auto",
}).appendTo("head");

Or using the traditional way:

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://checkout.stripe.com/checkout.js';
script.setAttribute('class', "stripe-button");
script.setAttribute("data-key", "pk_test_11a6LFgOQ9rZ3d54Qd0uBF8c");
script.setAttrubute("data-amount", document.querySelector('#amount').value);
script.setAttribute("data-name", "Oyon Shop");
script.setAttribute("data-description", "Thank you for puchasing!");
script.setAttribute("data-image", "/img/demo.png");
script.setAttribute("data-locale", "auto");

document.getElementsByTagName('head')[0].appendChild(script);