I'm working on a shopping cart that asks the user to check the box indicating they agree to the terms of service before they can "review order" and finally make the purchase.
I have to accomplish this with JavaScript by getting the element containing the "review order" and "continue shopping" buttons and changing the inner HTML to be what I need. I have to do it this way because the cart I am using does not give me full control over these elements in the cart source code.
Here is the code I originally came up with, which worked on Chrome, Edge, and other browsers, but not IE.
var x = document.getElementById('CHECKOUT_LINKS');
x.innerHTML = '<div class="checkoutLinksBottom"><input id="tosBox" type="checkbox" name="tosBox">I agree to the <a href="http://example.com/terms-of-service/" target="_blank">Terms of Service</a><br><a href="javascript:history.go(-1);" class="continueButton">Continue Shopping</a><a href="javascript:void(0)" id="reviewOrderButton" class="continueButton" onclick="clicker();">Review Order</a></div>';
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('#tosBox').addEventListener('change', changeHandler);
});
var checkbox = document.getElementById("tosBox");
checkbox.checked = true;
checkbox.checked = false;
function changeHandler() {
if (!tosBox.checked)
alert("You must agree to the Terms of Service");
}
function clicker() {
if (!tosBox.checked)
alert("You must agree to the Terms of Service");
else { // Go to review order page
}
}
As you can see the CHECKOUT_LINKS
element's inner HTML is changed to what I need on the fly as the page loads. The primary point is to add the id="tosBox"
element, then capture the click on id="reviewOrderButton"
element and filter it though the simple JS functions changeHandler()
and clicker()
.
In IE developer tools, the console reports 'tosBox' is undefined
when I click on id="reviewOrderButton"
element. This makes sense when looking at var checkbox = document.getElementById("tosBox");
the variable created is called checkbox
, but the variable I try to use later is called tosBox
. I simply changed checkbox
to tosBox
and then everything worked on IE as well.
What's shocking to me is that the original code worked on Chrome and Edge. How did it work? Should I expect it to work and IE is faulting?