使用 Ajax 提交后在同一页面中显示 HTML 表单值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15447889/
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
Display HTML form values in same page after submit using Ajax
提问by Saravanan Malar
I have a HTML form and I need to display the form field values below the form after user clicks the submit button. How can I do this using HTML and JavaScript Ajax?
我有一个 HTML 表单,我需要在用户单击提交按钮后在表单下方显示表单字段值。如何使用 HTML 和 JavaScript Ajax 执行此操作?
回答by Ojonugwa Jude Ochalifu
Here is one way to do it.
这是一种方法。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<script language="JavaScript">
function showInput() {
document.getElementById('display').innerHTML =
document.getElementById("user_input").value;
}
</script>
</head>
<body>
<form>
<label><b>Enter a Message</b></label>
<input type="text" name="message" id="user_input">
</form>
<input type="submit" onclick="showInput();"><br/>
<label>Your input: </label>
<p><span id='display'></span></p>
</body>
</html>
And this is what it looks like when run.Cheers.
这就是运行时的样子。干杯。
回答by Nenad Bulatovic
One more way to do it (if you use form), note that input type is button
另一种方法(如果您使用表单),请注意输入类型是按钮
<input type="button" onclick="showMessage()" value="submit" />
Complete code is:
完整代码为:
<!DOCTYPE html>
<html>
<head>
<title>HTML JavaScript output on same page</title>
<script type="text/JavaScript">
function showMessage(){
var message = document.getElementById("message").value;
display_message.innerHTML= message;
}
</script>
</head>
<body>
<form>
Enter message: <input type="text" id = "message">
<input type="button" onclick="showMessage()" value="submit" />
</form>
<p> Message is: <span id = "display_message"></span> </p>
</body>
</html>
But you can do it even without form:
但即使没有形式,你也可以做到:
<!DOCTYPE html>
<html>
<head>
<title>HTML JavaScript output on same page</title>
<script type="text/JavaScript">
function showMessage(){
var message = document.getElementById("message").value;
display_message.innerHTML= message;
}
</script>
</head>
<body>
Enter message: <input type="text" id = "message">
<input type="submit" onclick="showMessage()" value="submit" />
<p> Message is: <span id = "display_message"></span> </p>
</body>
</html>
Here you can use either submit or button:
在这里您可以使用提交或按钮:
<input type="submit" onclick="showMessage()" value="submit" />
No need to set
无需设置
return false;
from JavaScript function for neither of those two examples.
来自这两个示例的 JavaScript 函数。
回答by Optimus Prime
This works.
这有效。
<html>
<head>
<script type = "text/javascript">
function write_below(form)
{
var input = document.forms.write.input_to_write.value;
document.getElementById('write_here').innerHTML="Your input was:"+input;
return false;
}
</script>
</head>
<!--Insert more code here-->
<body>
<form name='write' onsubmit='return write_below(this);'>
<input type = "text" name='input_to_write'>
<input type = "button" value = "submit" />
</form>
<div id='write_here'></div></body>
</html>
Returning false from the function never posts it to other page,but does edit the html content.
从函数返回 false 永远不会将其发布到其他页面,但会编辑 html 内容。
回答by Oliver Paljak
Well this can be pretty tricky if you don't use AJAX. I definitely recommend it (you can find W3Schools tutorial here).
好吧,如果您不使用 AJAX,这可能会非常棘手。我绝对推荐它(你可以在这里找到 W3Schools 教程)。
But in this answer I am assuming that you don't want to use AJAX for some reason so the solution is going to be in pure JavaScript.
但是在这个答案中,我假设您出于某种原因不想使用 AJAX,因此解决方案将使用纯 JavaScript。
First, let's make our form (all sorts of inputs):
首先,让我们制作表单(各种输入):
<form id="form">
Name: <input name="full-name" type="text" />
<br />
Favourite image: <input name="favourite_image" type="file" accept="image/*" />
<br />
Sex: Male <input name="sex" value="male" type="radio" /> Female <input name="sex" value="female" type="radio" />
<br />
Date: <input name="date" type="date" />
<br />
Are you a web developer: <input name="web-developer" type="checkbox" />
<br />
Your favourite web language(s):
<br />
<select name="favourite-web-language" multiple="multiple">
<option>HTML</option>
<option>CSS</option>
<option>JavaScript</option>
</select>
<br />
Your favourite color: <input name="favourite-color" type="color" />
<br />
<textarea name="textarea-comment">Wassup!</textarea>
<br />
<button type="button" id="submit-button">Show my inputs</button>
<br />
<br />
<br />
<h3>Your inputs are:</h3>
<output id="output"></output>
Now it is time for JavaScript
Made this answer Object Oriented because it allows multiple forms to have this kind of script.
现在是 JavaScript
使这个答案面向对象的时候了,因为它允许多个表单具有这种脚本。
/**
* Class for getting form content
*
* @version 1.0.0
*/
class FormContent{
/**
* Create new form content object
*
* @param {HTMLFormElement} formElement Single form element
* @param {string} inputSelectors Selectors for elements which will be used to read and display data (like jQuery selectors: # for IDs, . for classes and so on). Separate multiple selectors with comas.
* @param {HTMLButtonElement | HTMLInputElement} submitButton Submit button to display form data (although the type should be always 'button')
* @param {Element} outputSection Section where the form data is displayed
* @since 1.0.0
*/
constructor(formElement, inputSelectors, submitButton, outputSection){
/**
* Disabled elements (values will not be shown in output). Values can be tag names, attribute 'type' values or certain element (inside form)
*
* @type {Array}
* @since 1.0.0
*/
this.disabledElements = ["button", "reset", "submit"];
/**
* Input elements node list (created by inputSelectors)
*
* @type {NodeList}
* @since 1.0.0
*/
var inputElements = formElement.querySelectorAll(inputSelectors);
/**
* Get input elements
*
* @see inputElements
* @return {NodeList} Input elements
* @since 1.0.0
*/
this.getInputElements = function(){ return inputElements; };
/**
* Get submit button
*
* @return {HTMLButtonElement} Submit button
* @since 1.0.0
*/
this.getSubmitButton = function(){ return submitButton; };
/**
* Get output section
*
* @see outputSection
* @return {NodeList} Output section
* @since 1.0.0
*/
this.getOutputSection = function(){ return outputSection; };
/**
* Empty input's alternative (print) value
*
* @type {string}
* @since 1.0.0
*/
this.emptyValueMessage = "Unknown";
/**
* Error message (when there is empty required fields)
*
* @type {string}
* @since 1.0.0
*/
this.errorMessage = "<h4 style='color:#FF0000;'>Please fill all the required inputs!</h4>";
/**
* Instance for this class
*
* @type {FormContent}
* @since 1.0.0
*/
var thisInstance = this;
if(submitButton && outputSection){
submitButton.onclick = function(){
thisInstance.onSubmitButtonClick();
};
}
}
/**
* When submit button is clicked
*
* @since 1.0.0
*/
onSubmitButtonClick(){
var outputMessage = (this.areRequiredInputsFilled()) ? this.getFormattedFormContent() : this.errorMessage;
this.printToOutput(outputMessage);
}
/**
* Are all the required inputs/fields filled?
*
* @return {boolean}
* @since 1.0.0
*/
areRequiredInputsFilled(){
for(var node of this.getInputElements()){
if(node.required && !node.value){
return false;
}
}
return true;
}
/**
* Print/display form data to output element
*
* @see getOutputSections()
* @since 1.0.0
*/
printToOutput(content){
this.getOutputSection().innerHTML = content;
}
/**
* Get form content/data which is formatted
*
* @return {string} Formatted form content
* @since 1.0.0
*/
getFormattedFormContent(){
var formContent = "";
var formData = this.getFormData();
for(var input in formData){
formContent += "<b>" + input + "</b>: " + formData[input] + "<br />";
}
return formContent;
}
/**
* Get raw form data
*
* @return {json} Form data
* @since 1.0.0
*/
getFormData(){
var formData = {};
var noNameCounter = 0;
var formInputs = this.getFormInputs();
for(var input of formInputs){
let inputName = input.name || "no_name_element_" + noNameCounter;
let inputValue = input.data || input.value || this.emptyValueMessage;
if(!input.name){
noNameCounter++;
}
formData[inputName] = inputValue;
}
return formData;
}
/**
* Get all the form input elements
*
* @return {Array} Inputs and values (form data)
* @since 1.0.0
*/
getFormInputs(){
var formInputs = [];
for(var input of this.getInputElements()){
if(!this.disabledElements.includes(input.tagName.toLowerCase()) && !this.disabledElements.includes(input.type) && !this.disabledElements.includes(input)){
if(input.type === "radio"){
if(input.checked){
formInputs.push(input);
}
}else if(input.type === "checkbox"){
input.value = (input.checked) ? true : false;
formInputs.push(input);
}else if(input.multiple){
formInputs.push(this.getMultipleInput(input));
}else if(input.value || input.innerHTML){
formInputs.push(input);
}else{
formInputs.push(input);
}
}
}
return formInputs;
}
/**
* Get input which has attribute multiple
*
* @param {HTMLInputElement} multipleInput Input with attribute multiple
* @return {HTMLInputElement} Input instance
* @since 1.0.0
*/
getMultipleInput(multipleInput){
var inputInstance = document.createElement("input");
inputInstance.name = multipleInput.name;
var values = [];
if(multipleInput.type !== "file"){
for(var option of multipleInput){
if(option.selected){
values.push(option.value);
}
}
}else{
for(var file of multipleInput.files){
values.push(file.name);
}
}
inputInstance.data = values.toString();
return inputInstance;
}
}
var forms = document.getElementsByTagName("form");
for(var form of forms){
let inputSelectors = "input, select, textaera";
let submitButton = form.querySelector("#submit-button");
let outputSection = form.querySelector("#output");
new FormContent(form, inputSelectors, submitButton, outputSection);
}
Basically this script loops through every single input element and uses name
and value
(or sometimes data
) attributes to display the form data.
基本上这个脚本循环遍历每个输入元素并使用name
和value
(或有时data
)属性来显示表单数据。
It recognizes attributes like multiple
and required
and functions accordingly. And it should work with every input element (text area, file uploader, color picker etc.).
它相应地识别像multiple
和这样的属性required
和功能。它应该适用于每个输入元素(文本区域、文件上传器、颜色选择器等)。
Github and live examples here.
Github 和现场示例在这里。
回答by Vikram S
var tasks = [];
var descs = [];
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
var rowCount = 1;
function addTasks() {
var temp = 'style .fa fa-trash';
tasks.push(document.getElementById("taskname").value);
descs.push(document.getElementById("taskdesc").value);
var table = document.getElementById("tasksTable");
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = tasks[rowCount - 1];
cell2.innerHTML = descs[rowCount - 1];
cell3.innerHTML = getDate();
cell4.innerHTML = '<td class="fa fa-trash"></td>';
rowCount++;
modal.style.display = "none";
}
function getDate() {
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var today = dd + '-' + mm + '-' + yyyy.toString().slice(2);
return today;
}
<html>
<body>
<!-- Trigger/Open The Modal -->
<div style="background-color:#0F0F8C ;height:45px">
<h2 style="color: white">LOGO</h2>
</div>
<div>
<button id="myBtn"> + Add Task  </button>
</div>
<div>
<table id="tasksTable">
<thead>
<tr style="background-color:rgba(201, 196, 196, 0.86)">
<th style="width: 150px;">Name</th>
<th style="width: 250px;">Desc</th>
<th style="width: 120px">Date</th>
<th style="width: 120px class=fa fa-trash"></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h3> Add Task</h3>
</div>
<div class="modal-body">
<table style="padding: 28px 50px">
<tr>
<td style="width:150px">Name:</td>
<td><input type="text" name="name" id="taskname" style="width: -webkit-fill-available"></td>
</tr>
<tr>
<td>
Desc:
</td>
<td>
<textarea name="desc" id="taskdesc" cols="60" rows="10"></textarea>
</td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="submit" value="submit" style="float: right;" onclick="addTasks()">SUBMIT</button>
<br>
<br>
<br>
</div>
</div>
</div>
</body>
</html>
回答by imulsion
<script type = "text/javascript">
function get_values(input_id)
{
var input = document.getElementById(input_id).value;
document.write(input);
}
</script>
<!--Insert more code here-->
<input type = "text" id = "textfield">
<input type = "button" onclick = "get('textfield')" value = "submit">
Next time you ask a question here, include more detail and what you have tried.
下次您在这里提出问题时,请提供更多详细信息以及您尝试过的内容。
回答by Vikas Gautam
Try this one:
试试这个:
onsubmit="return f(this.'yourfieldname'.value);"
I hope this will help you.
我希望这能帮到您。
回答by rose
display html form values in same page after clicking on submit button using JS & html codes. After opening it up again it should give that comments in that page.
使用 JS 和 html 代码单击提交按钮后,在同一页面中显示 html 表单值。再次打开它后,它应该在该页面中给出评论。