I have a magento
website, I am trying to scan a table for a discount code and update another part of the table if a discount code is present.
The code I am using to try and achieve this is below:
console.log("Discount Code Script Loaded");
$(function(){
if($('#checkout-review-table-wrapper p').text().replace(/W/g, '')=="NathanTest9856"){
console.log("Found code");
$('span.price p').html("£0.00");
console.log("Shipping Total Corrected");
} else{
console.log("Coupon Code Not Found")
}
console.log("Discount Code Script Completed");
});
console.log($('#checkout-review-table-wrapper p').text().replace(/W/g, ''));
the code of the page is simplified below:
<body>
<div id="checkout-review-table-wrapper">
<p>
Discount Code (NathanTest9856)
</p>
</div>
<span class="price">
<p>
£15.00
</p>
</span>
</body>
This can also be found in a jsfiddle at: https://jsfiddle.net/nlangerdevcenturion/qu6bvrc0/35/
The issue I seem to be facing is, it can’t detect the Discount code of NathanTest9856 within the p
tag.
As you can see from the following error: Uncaught TypeError: Cannot read property 'text' of null at centurion.js:12
2
Answers
The problem is the RegExp
/W/g
. This will replace all non-word character (spaces in this case) and you’ll remain with DiscountCodeNathanTest9856 which is not equal to NathanTest9856You could use a condition like this instead
Which will check that paragraph’s text for the existence of the (NathanTest9856) string.
You can use jquery’s
:contains
to check if an element contains something (in this case some text).Change:
to:
Updated code:
Updated fiddle: https://jsfiddle.net/qu6bvrc0/59/
Alternatively, you can use a multitude of vanilla javascript methods on
.text()
, see here for more: https://stackoverflow.com/a/1789952/2181514eg: