javascript html5 基本警报和文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14135837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
html5 basic alert and textbox
提问by user1942359
I am a newbie in HTML5 and javascript. I want an alert box to display data(firstname and lastname). Data must be taken from textboxes on the form. My code is below, but the alertbox doesn't work.
我是 HTML5 和 javascript 的新手。我想要一个警报框来显示数据(名字和姓氏)。数据必须取自表单上的文本框。我的代码如下,但警报框不起作用。
<!DOCTYPE html>
<html>
<body>
<form action="demo_form.asp" method="get">
First name: <input type="text" name="fname" /><br>
Last name: <input type="text" name="lname" /><br>
</form>
<script>
function display_alert()
{
alert(fname +lname);
}
</script>
<input type="button" onclick="display_alert()" value="Display alert box">
</body>
</html>
回答by Marcin Buciora
You need to give ids to inputs tags
您需要为输入标签提供 id
<form>
<input id="a" type="text"/>
<input id="b" type="text"/>
<input type="button" onclick="display_alert();" />
</form>
and then use them inside your js code:
然后在你的 js 代码中使用它们:
<script lang="javascript">
function display_alert() {
var fn = document.getElementById('a');
var ln = document.getElementById('b');
alert(fn.value + ' ' + ln.value);
}
</script>
回答by KarSho
You can use jQuery.
您可以使用 jQuery。
html:
html:
First name: <input type="text" id='fname' /><br>
Last name: <input type="text" id='lname'/><br>
<input type="button" onclick="display_alert();" value="Display alert box">
script:
脚本:
function display_alert() {
fname = $('#fname').val();
lname = $('#lname').val();
alert(fname+' '+lname);
}?
Jquery might be useful for the future.
Jquery 可能对未来有用。
回答by Rikesh
You need to get values using getElementsByNamefunction in your script.
您需要在脚本中使用getElementsByName函数获取值。
Try changing your script with below one.
尝试使用以下脚本更改您的脚本。
<script>
function display_alert()
{
var fname = document.getElementsByName("fname")[0].value;
var lname = document.getElementsByName("lname")[0].value;
alert(fname + ' ' + lname);
}
</script>
Note:Just for your information, there is no relation with HTML5
to this.
注:仅供参考,与HTML5
此无关。