Question

I have an HTMLScriptObject that I am trying to modify a data attribute. I need to calculate the data-amount and set that value which is used in the script but am having no luck. I have =the javascript working "correctly" (according to the final value in log), but I can't seem to be able to change the data-amount attribute in the markup below. Here is the relevant HTML markup:

<script src="/static/js/filename.js"></script>
<form action="" method="POST">
  <script id="stripe-button"
    src="https://checkout.stripe.com/checkout.js" 
    data-amount="0"
    ...
    >
  </script>
</form>

And here is the relevant filename.js:

$(document).ready(function(){
    $( ".btn-service" ).click(function(){

        //add service price to the subtotal
        subtotalObj = $( "#subtotal" );
        price = parseInt($(this).data("price"));
        previousSubTotal = parseInt($( "#subtotal" ).text());

        if ($(this).hasClass( "btn-added" )) {
            nextSubTotal = previousSubTotal + price;
            $(this).text("Remove From Cart");
        }
        else if ($(this).hasClass( "btn-add" )) {
            nextSubTotal = previousSubTotal - price;
            $(this).text("Add To Cart");
        }

        //update the values
        subtotalObj.text(nextSubTotal);
        var stripe = document.getElementById('stripe-button');
        stripe.setAttribute('data-amount', nextSubTotal);
        console.log(stripe.getAttribute('data-amount')); //this returns the correct amount.
    });
});

The console log at the end of the data-amount property returns the value I'm looking for, but when I look at the markup source the data-amount value is still at 0. Not sure why the data-amount is not being changed.

I've tried also using the attr() method but JQuery puts out an error message: Object # has no method 'attr'. I've also tried using the data('amount', value) but that results in the same error - no method 'data'.

Was it helpful?

Solution

If by "in the markup " you mean using the browser's "view source" function, then you're looking at the page source, it isn't updated to reflect DOM changes (it's the source, not the current document).

Use a web inspector or debugger to see what the current DOM looks like as markup, or get the form's innerHTML property.

Also, you should declare all those variables with var to keep them local.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top