如何在 HTML 页面上向用户显示输入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19443834/
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
How to display input back to the user on an HTML page?
提问by Ashok Kumar
I am new to HTML and I am trying to create a script to display user input in a message box. I have created a textbox and validated it with a regular expression (alphabet only).
我是 HTML 的新手,我正在尝试创建一个脚本来在消息框中显示用户输入。我创建了一个文本框并使用正则表达式(仅限字母)对其进行了验证。
Now I need to display the user input in the page itself. How can I do this with JavaScript?
现在我需要在页面本身中显示用户输入。我怎样才能用 JavaScript 做到这一点?
I need to display all the user inputs in the page itself. I need to display the two letter word in one container and three letter word in another container.
我需要在页面本身中显示所有用户输入。我需要在一个容器中显示两个字母的单词,在另一个容器中显示三个字母的单词。
This is the code I tried.
这是我试过的代码。
<html>
<head>
<style type="text/css">
</style>
<script type="text/javascript">
function Allow() {
if (!user.title.value.match(/[a-zA-Z]$/) && user.title.value != "") {
user.title.value = "";
alert("Please Enter only alphabets");
}
}
var titles = [];
var titleInput = document.getElementById("title");
var messageBox = document.getElementById("display");
function insert( ) {
titles.push(titleInput.value);
clearAndShow();
}
function clearAndShow() {
// Clear our fields
titleInput.value = "";
// Show our output
messageBox.innerHTML = "";
messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
</script>
</head>
<body>
<p>form input</p>
<form name="user" action="" onsubmit=" " method="post">
User<input id="title" type="text" maxlength="4" onkeyup=" Allow() " >
<input type="submit" value="Save/Show" onclick=" insert() " />
</form>
<div id="display"></div>
</form>
</body>
</html>
回答by Ben
For a basic client-side validation, start with document.getElementById('foo')
and HTML formed like <input id='foo' value='bar' />
. You can validate and repopulate using .value
, somthing like this:
对于基本的客户端验证,从document.getElementById('foo')
和 HTML开始,如<input id='foo' value='bar' />
. 您可以使用 验证和重新填充.value
,如下所示:
var foo = document.getElement('foo');
if (foo.value.match('your regex')) {
foo.value = foo.value.substr(0, 3);
}
For server-side saving and validation, unfortunately you can't do this with only Javascript.
对于服务器端保存和验证,不幸的是,您不能仅使用 Javascript 来执行此操作。
Javascript is client-side, which means it's trapped inside your browser.
Javascript 是客户端,这意味着它被困在您的浏览器中。
To send values back to the server, you need something like PHP or Ruby to receive POST
ed form values and write them to a file. Javascript can't write to files for security reasons.
要将值发送回服务器,您需要像 PHP 或 Ruby 这样的东西来接收POST
ed 表单值并将它们写入文件。出于安全原因,Javascript 无法写入文件。
To use Ruby or PHP with Javascript, you could do it dynamically with an Ajax request (intermediate skill level) or by submitting a <form>
element (beginner skill level).
要将 Ruby 或 PHP 与 Javascript 结合使用,您可以通过 Ajax 请求(中级技能水平)或通过提交<form>
元素(初级技能水平)来动态完成。
UPDATE...after you showed some code :)
更新......在你展示了一些代码之后:)
You need to put the <script>
tag afterthe body in the HTML is finished. When you do document.getElementById("title")
, it stays null because the HTML isn't finished rendering!
您需要在 HTML 中的正文完成后放置<script>
标记。当你这样做时,它保持为空,因为 HTML 没有完成渲染!document.getElementById("title")
Otherwise, you did everything right. Here's your code, a little cleaner, and working.
否则,你做的一切都是正确的。这是你的代码,更简洁,并且可以工作。
<html><head></head><body>
<input id="title" type="text" maxlength="4" onkeyup="Allow()" >
<input type="submit" value="Save/Show" onclick="insert()" />
<div id="display"></div>
<script type="text/javascript">
var titles = [];
var titleInput = document.getElementById("title");
var messageBox = document.getElementById("display");
function Allow(){
if (!user.title.value.match(/[a-zA-Z]$/) && user.title.value !="") {
user.title.value="";
alert("Please Enter only alphabets");
}
}
function insert () {
titles.push(titleInput.value);
clearAndShow();
}
function clearAndShow () {
titleInput.value = "";
messageBox.innerHTML = "";
messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
}
</script>
</body>
</html>
Your code didn't include the part about the "two letter container" and the "three letter container" so the best I can do there is recommend substr()
again.
您的代码没有包含关于“两个字母容器”和“三个字母容器”的部分,所以我能做的最好的substr()
再次推荐。
LAST UPDATE
最后更新
Here's a basic implementation of two and three letter strings, input delimited using commas like foo,bar,fo,ba
:
这是两个和三个字母字符串的基本实现,输入使用逗号分隔,例如foo,bar,fo,ba
:
<html><head></head><body>
<input id="title" type="text" >
<input type="submit" value="Save/Show" onclick="clearAndShow()" />
<div id="display2letter"></div>
<div id="display3letter"></div>
<script type="text/javascript">
var titleInput = document.getElementById("title");
var display2letter = document.getElementById("display2letter");
var display3letter = document.getElementById("display3letter");
function clearAndShow () {
// Split input box value by comma
titles = titleInput.value.split(",");
// Reset display divs
display2letter.innerHTML = "";
display3letter.innerHTML = "";
// Cache length so it's not recalculated on each iteration.
var len = titles.length;
var twoletter = [];
var threeletter = [];
for (i = 0; i < len; i++) {
// Check for a-z, A-Z, length 2 or 3
if (!titles[i].match(/^[a-zA-Z]{2,3}$/)) {
throw new Error("Please use only alphabet letters.");
break;
}
// Dump into storage arrays.
if(titles[i].length == 2) {
twoletter.push(titles[i]);
}
else {
threeletter.push(titles[i]);
}
}
display2letter.innerHTML += "Titles, 2 letters: " + twoletter.join(", ") + "<br/>";
display3letter.innerHTML += "Titles, 3 letters: " + threeletter.join(", ") + "<br/>";
}
</script>
</body>
</html>
回答by Manav Kataria
You can (temporarily; only on the client side) store user input in javascript variables. Create a container (div) and use Javascript HTML DOM API to update it with the required value.
您可以(暂时;仅在客户端)将用户输入存储在 javascript 变量中。创建一个容器 (div) 并使用 Javascript HTML DOM API 将其更新为所需的值。
Here is the JavaScript DOM reference guide from w3schools: http://www.w3schools.com/jsref/
以下是 w3schools 的 JavaScript DOM 参考指南:http: //www.w3schools.com/jsref/
回答by w3bMak3r
You might want to try looking into JQuery for an easy way to do this.. What you are doing is simple enough where you probably don't need JQuery but would make it a lot simpler for learning.
您可能想尝试查看 JQuery 以找到一种简单的方法来执行此操作。您所做的很简单,您可能不需要 JQuery,但会使学习变得更简单。
Here is a quick jsFiddle give a short example of getting values from a text box and appending them to another element.
这是一个快速的 jsFiddle,给出了从文本框中获取值并将它们附加到另一个元素的简短示例。
HTML:
HTML:
<label>Enter you name:</label><input id="name" type ="text"/><br/>
<h1 id="message"></h1>
Javascript:
Javascript:
$( document ).ready(function() {
$('#name').change(function(){
$('#message').html('Hello ' + $('#name').val());
});
});
And here is the documentation on getting values easily with jQuery:
这是有关使用 jQuery 轻松获取值的文档:
Again jQuery is not required but since you appear new it might be easier.
同样,jQuery 不是必需的,但由于您看起来很新,它可能会更容易。
回答by Saul Berardo
Here is a complete example taken from w3schoolswhich shows how to accomplish what you want. If you want to save the user input to show it to the user later, take a look at a tutorial about cookies.
这是一个来自w3schools的完整示例,它展示了如何完成你想要的。如果您想保存用户输入以稍后向用户显示,请查看有关 cookie的教程。
<!DOCTYPE html>
<html>
<body>
<p>Click the button to demonstrate the prompt box.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction()
{
var x;
var person=prompt("Please enter your name","Harry Potter");
if (person!=null)
{
x="Hello " + person + "! How are you today?";
document.getElementById("demo").innerHTML=x;
}
}
</script>
</body>
</html>