如何在提交时调用 javascript 函数来为输入赋值?(ACE 编辑)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12674023/
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 call a javascript function on submit to assign a value to an input? (ACE Editor)
提问by tempy
My goal is to send the code inside the ACE Editor to as a variable to the send.php
PHP file. I tried this in many different methods but I can't assign the code inside the editor to the form input.
我的目标是将 ACE 编辑器中的代码作为变量发送到send.php
PHP 文件。我尝试了许多不同的方法,但我无法将编辑器内的代码分配给表单输入。
JavaScript
JavaScript
This javascript function should assign a value to an element with the id="code"
, which is: <input type="hidden" id="code" value="" />
.
这个 javascript 函数应该为带有 的元素分配一个值id="code"
,即:<input type="hidden" id="code" value="" />
。
editor.getSession().getValue();
returns the code that is inside the editor.
editor.getSession().getValue();
返回编辑器内的代码。
<head>
<script>
function getVal() {
document.getElementById('code').value = editor.getSession().getValue();
}
</script>
</head>
HTML
HTML
Now, <form onsubmit="getVal();"
should execute function getVal()
when a user submits the form, so that the code
input will have a value when sending the inputs to the send.php
file.
现在,<form onsubmit="getVal();"
应该function getVal()
在用户提交表单时执行,以便在将code
输入发送到send.php
文件时输入将具有值。
<body>
<div>
<form onsubmit="getVal();" method="post" action="send.php">
<label for="Name">From:</label>
<input type="text" name="Name" id="Name" />
<label for="Address">To:</label>
<input type="text" name="Address" id="Address" />
<label for="Subject">Subject:</label>
<input type="text" name="Subject" id="Subject" />
<input type="hidden" id="code" value="" />
<div id="editor"> //ACE Editor
</div>
<input type="submit">
</form>
</div>
回答by tempy
This function is the one I needed in order to make this work:
为了完成这项工作,我需要这个函数:
function getVal()
{
var editor = ace.edit("editor");
// this line is necessary
// "editor" is the id of the ACE editor div
var code = editor.getSession().getValue();
document.getElementById('code').value = code;
}
回答by stkover_0
The code is correct, editor.getSession().getValue() is null so it writes nothing!
代码是正确的, editor.getSession().getValue() 为空,所以它什么都不写!