【问题标题】:Make a Prompt box create an alert使提示框创建警报
【发布时间】:2016-07-28 02:56:52
【问题描述】:

我正在尝试使用 Javascript 创建一个表单。

我需要表单中的姓名和年龄。输入字段后,您单击提交。提交需要创建一个提示,让您输入新的背景颜色。

单击确定后,我需要一条警报,上面写着(字段名称中的名称“您最喜欢的颜色已应用于页面背景”“您的年龄是(显示年龄字段中的年龄)

示例:Brad 将您最喜欢的颜色应用于页面背景。 你的年龄是 33 岁。我不知道如何让 javascript 获取在姓名和年龄字段中输入的姓名和年龄。

HTML 代码:

    <form>
       First name:<br>
          <input type="text" name="firstname" id="name"><br>
      Age:<br>
         <input type="text" name="txtage" id="age"><br>
         <input type="submit" name="submit" id="process" onclick="MyFunction">
    </form>

外部 Java 脚本:

function MyFunction() {
  x = prompt("Enter the color you want on the Background???");
  document.body.style.backgroundColor = x; 
  if (x != null){       
    alert("(need name from form)Your favorite color was applied to the background of the page, your age is (need age from form) ");
  }
}   

【问题讨论】:

  • 您发布的 java script 代码中没有年龄或姓名字段 - 请发布相关代码,而不是工作 sn-p
  • 表单是用 HTML 编写的,我有一个姓名字段和一个年龄字段。名称字段具有 ID=Name,年龄字段具有 ID=Age,提交按钮具有 ID=进程。单击提交按钮后,提供的代码会提示弹出一个框。您输入您喜欢的颜色,背景更改为您选择的颜色。我需要的是在提示框上单击“确定”后弹出的警报框说。 "(Name from Name field) 你最喜欢的颜色已经被选中,你的年龄是(Age from Age field)" 我是一个新的学生,在启动Java时遇到了麻烦。

标签: javascript alert prompt


【解决方案1】:

从 DOM 中获取 &lt;input&gt; 元素的一种方法是将其 id 与 document.getElementById 一起使用。从此&lt;input&gt; 获取输入文本的方法来自其.value 属性。

因此,要从 id name 的输入中获取字符串文本,您可以这样做

var name = document.getElementById("name").value;

这可能是这样的:

function MyFunction() {
  x = prompt("Enter the color you want on the Background???");
  document.body.style.backgroundColor = x; 

  var name = document.getElementById("name").value;
  var age = // ...get the age in a similar manner

  if (x != null) {       
    // concat strings using the + operator
    alert(name + "Your favorite color was applied to the background of the page, your age is " + age);
  }
}   

【讨论】:

  • 感谢工作。但是你如何在输入之间获得一个空间?当 Java 运行时,会出现警报“Bradyour favorite color was applied to the background. Your age is33” name 元素和 age 元素不会与文本隔开。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-19
  • 1970-01-01
相关资源
最近更新 更多