简体   繁体   English

制作姓名和年龄输入警报器

[英]Making a name and age input alerter

basically I am trying to make a form so that sends the user an alert when you press the button with their name and age, my code is below and I have also been doing this on my website: http://js.blazedpanda.com/ 基本上,我正在尝试制作一个表格,以便在您按用户名称和年龄的按钮时向用户发送警报,我的代码在下面,我也在我的网站上进行过此操作: http : //js.blazedpanda.com /

var x=document.getElementById("name").value;
var y=document.getElementById("age").value;

function nameAge()
{
alert("Hello"+" "+x+" "+"who is"+" "+y);
}

If you could come up with a solution for this please help, this is probably really basic but I can't find a simple tutorial anywhere. 如果您可以提出解决方案,请帮忙,这可能确实很基础,但是我在任何地方都找不到简单的教程。 Thanks, Peter. 谢谢,彼得。

Edit: 编辑:

Thanks will have it fixed now, nice and quick responses :P 谢谢,现在将其修复,尼斯和快速的回​​复:P

Put first lines inside your function , like this: 在函数中放入第一行,如下所示:

function nameAge()
{
  var x=document.getElementById("name").value;
  var y=document.getElementById("age").value;
  alert("Hello"+" "+x+" "+"who is"+" "+y);
}

Because you want to get current values , so do it when user actually press the button. 因为您想获取当前值,所以在用户实际按下按钮时执行此操作。 When you define x and y variables outside of function they are assigned with undefined because of name and age elements are not exist yet. 当您在函数外部定义xy变量时,由于nameage元素尚不存在,它们将被分配为undefined

Looking at the page you linked, your error lies in the fact that you are defining x and y before the <input> elements are loaded. 查看链接的页面,您的错误在于,在装入<input>元素之前定义xy Thus, you receive an error. 因此,您会收到一个错误。 You want to encapsulate these within the function nameAge() 您想将它们封装在函数nameAge()

If you dont know Jquery yet, do this 如果您还不了解Jquery,请执行此操作

<input type="text" id="name" />
<input type="text" id="age" /> 

    function nameAge()
    {
    var x=document.getElementById("name").value;
    var y=document.getElementById("age").value;

    alert("Hello"+" "+x+" "+"who is"+" "+y);
    }

If you put it inside, it will update whenever you click the bottom. 如果放在里面,只要单击底部,它就会更新。

You just need to check the values of the name and age inside the function: 您只需要检查函数内部的名称和年龄值:

function nameAge()
{
   var x=document.getElementById("name").value;
   var y=document.getElementById("age").value;
   alert("Hello "+x+" who is "+y);
 }

And then just call the "onclick" event on the element you want to click 然后只需在要单击的元素上调用“ onclick”事件

<button name="myButton" onclick="javascript:nameAge();" /> 

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

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