0

I am trying to send the text typed in to a box via a link. Please see my code below. It isn't sending through for some reason?

<script>
    var discountCode = document.getElementById("discountCode").value;
        openPage = function() {
        location.href = "payment.php?discount="+discountCode;
    }                       
</script>
<a href ="javascript:openPage()" class="btn btn-warning">Purchase</a>

1 Answer 1

1

You're reading the value as soon as the page loads, not when the link is clicked. You just need to move the line into the function:

<script>
    openPage = function() {
        var discountCode = document.getElementById("discountCode").value;
        location.href = "payment.php?discount="+discountCode;
    }                       
</script>
<a href ="javascript:openPage()" class="btn btn-warning">Purchase</a>

Or alternatively just get a reference to the element when the page loads (assuming this script is after the discountCode element), then read the value in the function:

<script>
    var discountCode = document.getElementById("discountCode");
    openPage = function() {
        location.href = "payment.php?discount="+discountCode.value;
    }                       
</script>
<a href ="javascript:openPage()" class="btn btn-warning">Purchase</a>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.