How to prevent cursor jump to next line in fixed column textarea

不羁岁月 提交于 2021-02-15 07:14:51

问题


I have a textarea with the following HTML...

 <textarea id="inputFreeContentArea" cols="16" rows="6" maxlength="96" wrap="hard"></textarea>

When the user enters text, I want the cursor to stop moving when 16 characters are entered in a line, it should not automatically move to next line, only if the user hits the enter key. Furthermore, it should not be possible to exceed 6 rows.

How can this be done?


回答1:


There's not a simple way to achieve what you want, that would require a lot of code and input checking. Instead, you could use a wrapper and six input elements, style them a bit, and collect the values to a hidden input ex. realtime or in a form validator. Something like this:

function createTxtarea(parent, cols) {
  // Set the cols of the "textarea"
  const inputs = parent.querySelectorAll('input');
  inputs.forEach(input => input.setAttribute('maxlength', cols));
  // Add listener for Enter and ArrowUp/down keys
  const focusTo = {
    Enter: (e) => e.target.nextElementSibling,
    ArrowDown(e) {return this.Enter(e);},
    ArrowUp: (e) => e.target.previousElementSibling
  };
  parent.addEventListener('keydown', (e) => {
    const key = e.key;
    if (typeof focusTo[key] === 'function') {
      e.preventDefault();
      const prext = focusTo[key](e);
      if (prext) prext.focus();
    }
    // Collect the value here if needed
  });
}

createTxtarea(document.getElementById('area1'), 16);
.txtarea {
  border: 1px solid #ccc;
  padding: 1px;
  display: inline-block;
}
.txtarea input {
  border: none;
  display: block;
}
<form>
  <div id="area1" class="txtarea">
    <input type="text" name="area1[]">
    <input type="text" name="area1[]">
    <input type="text" name="area1[]">
    <input type="text" name="area1[]">
    <input type="text" name="area1[]">
    <input type="text" name="area1[]">
    <input type="text" name="area1[]">
  </div>
</form>

Suffixing the input names with [] makes them available as an array at the back-end, that way you can easily extract a single value from the inputs at the server too.

You can improve the basic code. It is easy to create multiple "txtareas", and the code can be converted to OOP if needed, and it's possible to create the inputs and even the parent element dynamically.

The code is ignored in phones, but filling the "txtarea" is still fluent. If you added the maxlength attributes to HTML, "txtarea" would work more fluently than a customized real textarea element, if JS is turned off.



来源:https://stackoverflow.com/questions/58626735/how-to-prevent-cursor-jump-to-next-line-in-fixed-column-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!