I am trying to setup a simple form with the particularity that if the user inputs a text that is wider than the textarea
, this will automatically resize. To be clear, I would like to have the same behavior than the property contenteditable="true"
in a span
tag.
<form action="/form" method="POST" style="margin-top: 100px;">
<p>
My name is <textarea name="name" cols="10" rows="1" placeholder="enter name"></textarea> and I come from a village called <textarea name="village" cols="10" rows="1" placeholder="enter village"></textarea>
. Everybody from the village of <textarea cols="10" rows="1" placeholder="enter village"></textarea> knows that my name is <textarea cols="10" rows="1" placeholder="enter name"></textarea>
</p>
<p>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
I found a very similar question for the height of a textarea so I just tried to adapt the js code for the width. Unfortunately, it does work for the height (see picture) but not for the width. What am I missing?
<script>
const tx = document.getElementsByTagName("textarea");
for (let i = 0; i < tx.length; i++) {
tx[i].setAttribute("style", "width:" + (tx[i].scrollWidth) + "px;overflow-x:hidden;");
tx[i].addEventListener("input", OnInput, false);
}
function OnInput() {
this.style.width = "auto";
this.style.width = (this.scrollWidth) + "px";
}
</script>