Search code examples
javascriptformstextarea

How to move individual lines up-down in textarea using Javascript


I am working on a project where I am pre-populating a form text area using mysql. I would like to know how I can rearrange the order of the values using javascript by clicking on a line of text and pressing up/down arrow key.

I found some codes that allows to re-order form select values. I wanted to use this as a starting point, but have no idea how to modify this to make it work with the text area. Any help is apprecaited.

Working code for Select

<select id="towns" size="5">
<option>Sofia</option>
<option>Varna</option>
<option>Plovdiv</option>
<option>Ruse</option>
</select>


<button id="btnUp" onclick="move(-1)">&uparrow;</button>
<button id="btnDown" onclick="move(+1)">&downarrow;</button>

<script>
function move(direction) {
    let OptionToMove = $('#towns option:selected');
    if (direction == -1) {
        OptionToMove.insertBefore(OptionToMove.prev());
    }
    if (direction == +1) {
        OptionToMove.insertAfter(OptionToMove.next());
    }
}
</script>

Need to be able to make this work for the text area (example). Tried using

<textarea name='city' id='city' cols='30' rows='10'>
Sofia
Varna
Plovdiv
Ruse
</textarea>
<input type="button" value="&uparrow;" id="btnUp" onclick="move(-1)"></input>
<input type="button" value="&downarrow;" id="btnDown" onclick="move(+1)"></input>
<script>
function move(direction) {
    let OptionToMove = $('#city toggle:selected');
    if (direction == -1) {
        OptionToMove.insertBefore(OptionToMove.prev());
    }
    if (direction == +1) {
        OptionToMove.insertAfter(OptionToMove.next());
    }
}
</script>

Solution

  • I found the cursor's position and then switched the two strings.

    function move(direction) {
      let lines = $('#city')[0].value.split('\n');
      let index = $('#city').prop("selectionStart");
      let i = 0;
      while (index > 0 && index >= lines[i].length) {
        if (i > 0) {
          index--;
        }
        index -= lines[i].length;
        i++;
      }
      if (i+direction < 0 || i+direction > lines.length) return;
      let temp = lines[i+direction];
      lines[i+direction] = lines[i];
      lines[i] = temp;
      $('#city')[0].value = lines.join("\n");
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <textarea name='city' id='city' cols='30' rows='10'>
    Sofia
    Varna
    Plovdiv
    Ruse
    </textarea>
    <input type="button" value="&uparrow;" id="btnUp" onclick="move(-1)"></input>
    <input type="button" value="&downarrow;" id="btnDown" onclick="move(+1)"></input>