I think the problem is you are submitting the form and setting text at the same time.
Try to use e.preventDefault(); to prevent form from submition and run your code before form submition.
take a look at this
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_textarea_value2
First select your form then add a “submit” event listener to form and add a callback function with passing event, inside the callback function call event.preventDefault() method and your setText() function.
const form = document.querySelector("form");
form.addEventListener("submit", e => {
e.preventDefault();
setText()
})
function setText() {
var tasks = document.getElementById('tasks');
var message = document.getElementById('message');
message.value = tasks.value + message.value;
}
<form>
<select id="tasks">
<option value="texthere 1">forage</option>
<option value="texthere 2">attack</option>
<option value="texthere 3">defend</option>
</select><br />
<input type="submit" class="button" name="submit" value="Post reply" tabindex="3" accesskey="s"><br />
<textarea id="message" name="message" rows="20" cols="70" tabindex="2">message</textarea>
</form>
Upon hitting the “post thread” button, I want it to add custom text to the textarea depending on what dropdown is selected in a select box. I have this script in the head of the newthread template but yet it still won’t work upon submitting. am I doing something wrong?
function setText() {
var tasks = document.getElementById('tasks');
var message = document.getElementById('message');
message.value = tasks.value + message.value;
}
<form>
<select id="tasks">
<option value="texthere 1">forage</option>
<option value="texthere 2">attack</option>
<option value="texthere 3">defend</option>
</select><br/>
<input type="submit" class="button" name="submit" value="Post reply" onClick="setText();" tabindex="3" accesskey="s" /><br/>
<textarea id="message" name="message" rows="20" cols="70" tabindex="2">message</textarea>
</form>
I made you a working snippet. Please make it into a
Note you should never assign click event handlers to a submit button. Use the submit event. Also not you will not see the message since the form is submitted and the page is unloaded