简体   繁体   English

onclick事件触发时调用的函数中的Javascript开关语句

[英]Javascript switch statement within a function that is called when the onclick event fires

My HTML is this: 我的HTML是这样的:

 <h3>Please enter your discount code</h3>
    <input type="text" name="discountCode" id="discountCode">
    <div id="message"></div>
    <button id="myButton"  onclick="myFunction()">Click Me</button>

When I click the button, I want the call to myFunction() fire on the event. 当我单击按钮时,我希望对myFunction()的调用在事件上触发。

My JavaScript is this: 我的JavaScript是这样的:

 function myFunction(){
    var discount;
    var discount = document.getElementById("discountCode").innerHTML;
    switch(discount){
        case "SAVE10":
        document.getElementById("message").innerHTML = "you are saving 10% on this order.";
        break;

        case "SAVE15":
        document.getElementById("message").innerHTML = "you are saving 15% on this order.";
        break;

        default:
        document.getElementById("message").innerHTML = "please enter a valid discount code.";
        break;
    }
}

I want to output the messages to the div element of "message". 我想将消息输出到“ message”的div元素。 When I run this code and enter a discount code, the only line that outputs to the message div is the default line: 当我运行此代码并输入折扣代码时,输​​出到消息div的唯一行是默认行:

please enter a valid discount code. 请输入有效的折扣代码。

Can anyone steer me in the right direction. 谁能引导我朝正确的方向前进。

Thanks! 谢谢!

Use .value instead of .innerHTML to get value from input tag. 使用.value而不是.innerHTML来从input标记中获取价值。

Check below: 检查以下内容:

 function myFunction() { var discount = document.getElementById("discountCode").value; switch (discount) { case "SAVE10": document.getElementById("message").innerHTML = "you are saving 10% on this order."; break; case "SAVE15": document.getElementById("message").innerHTML = "you are saving 15% on this order."; break; default: document.getElementById("message").innerHTML = "please enter a valid discount code."; break; } } 
 <h3>Please enter your discount code</h3> <input type="text" name="discountCode" id="discountCode"> <div id="message"></div> <button id="myButton" onclick="myFunction()">Click Me</button> 

Also removed var discount you declared twice. 还删除了您两次声明的var discount That was not required. 那不是必需的。

Read this for more information : https://www.w3schools.com/jsref/prop_text_value.asp 阅读此以获取更多信息: https : //www.w3schools.com/jsref/prop_text_value.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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