简体   繁体   中英

Validate Coupon Codes with Javascript

I am trying to get the code below to work. If i enter in the correct coupon code it still give me the "Sorry, The Coupon Code you entered is invalid. Please check and try again!" message.

Here is the javascript code:

<script language = "javascript"> 
function validate(coupon) { 
codes = new Object();
codes.GOLD20 = 20;
codes.GOLD = 30;
codes.GOLD40 = 40;
codes.GOLD50 = 50;

if (codes[coupon]) 
 { 
 window.alert("Coupon Code Accepted! Click the Order button!"); 
 } 
else 
 { 
 window.alert("Sorry, The Coupon Code you entered is invalid. Please check and try again!"); 
 } 
} 
</script>

Here is the html:

<input type="text" name="text1"> 
<input type="button" value="Validate Coupon" name="Submit" 
    onclick="validate()">` 

If you see any errors in my code please let me know or if you you know why i am not getting the alert for the Coupon code accepted please let me know.

It's because your no value is passed to validate. When you click, validate() gets called, with no parameter, so coupon is undefined.

The HTML should be:

<input type="text" name="text1"> 
   <input type="button" value="Validate Coupon" name="Submit" 
   onclick="validate(document.getElementsByName('text1')[0].value)">

Live JSFiddle Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM