mur7ay
mur7ay

Reputation: 833

Undefined value returned

I have a simple Stripe form that contains just some random value right now and I'm trying to grab that value but when I place it in a console.log it's returning an undefined value although there's one there. I've tried several solutions, but they simply haven't worked. I'm trying to just grab the text of 'work'. Anyone have a clue to whats going on?

HTML - Head

<head>
  <script src="https://js.stripe.com/v3/"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js">
  </script>
</head>

HTML - Form

<body>

<h3 id="work" value="400">500</h3>

<form action="/charge" method="post" id="payment-form">
  <div class="form-row">

    <label for="card-element">
      Credit or debit card
    </label>

    <div id="card-element">
      <!-- a Stripe Element will be inserted here. -->
    </div>

    <!-- Used to display form errors -->
    <div id="card-errors"></div>
  </div>
  <button>Submit Payment</button>
</form>
</body>

This is also located within my one HTML file as the form:

var card = elements.create('card', {style: style});

card.mount('#card-element');

card.addEventListener('change', function(event) {
  ...
});

// Handle form submission
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
  ...
});

function stripeTokenHandler(token) {

  var form = document.getElementById('payment-form');
  var hiddenInput = document.createElement('input');
  var totalAmount = document.createElement('input');

  hiddenInput.setAttribute('type', 'hidden');
  hiddenInput.setAttribute('name', 'stripeToken');
  hiddenInput.setAttribute('value', token.id);

  totalAmount.setAttribute('type', 'hidden');
  totalAmount.setAttribute('name', 'totalAmount');
  totalAmount.setAttribute('value', $('#work').innerHTML); //<-- Trying to get the value here

  form.appendChild(hiddenInput);
  form.appendChild(totalAmount);
  console.log(totalAmount);

  var formData = JSON.stringify({
    mytoken: token.id,
    totalAmount: totalAmount.value
  });

  console.log(formData); //<-- showing that it's undefined

  $.ajax({
    ...
  });

  // form.submit();
}
</script>

Result

enter image description here

Upvotes: 0

Views: 74

Answers (2)

YouneL
YouneL

Reputation: 8369

You have to use .text() method since you are using jquery $ selector:

$('#work').text()

In native javascript:

document.getElementById('work').innerText

Upvotes: 2

Ele
Ele

Reputation: 33726

Change this:

$('#work').innerHTML

To this:

$('#work').html()

If you want to use innerHTML from a JQuery object, you can use the following:

$('#work')[0].innerHTML

or pure Javascript

document.getElementById('work').innerHTML

Hope it helps!

Upvotes: 2

Related Questions