How to call a javascript function on submit to assign a value to an input? (ACE Editor)
-
12-12-2019 - |
Question
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.
JavaScript
This javascript function should assign a value to an element with the id="code"
, which is: <input type="hidden" id="code" value="" />
.
editor.getSession().getValue();
returns the code that is inside the editor.
<head>
<script>
function getVal() {
document.getElementById('code').value = editor.getSession().getValue();
}
</script>
</head>
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.
<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>
Solution
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;
}
OTHER TIPS
The code is correct, editor.getSession().getValue() is null so it writes nothing!