Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
835 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...