Home > Software design >  Input paste long text split to other input (jquery)
Input paste long text split to other input (jquery)

Time:06-03

I am new to HTML and jQuery. If I paste the long text to first input, I wanted it to be automatically split to other input (based on space). Is it possible to do it in jQuery? Please help.

This is the code:

https://codesandbox.io/s/kind-boyd-jnig1b?file=/index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Static Template</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
  <body>
    <!-- if type this long text to first input ,
      Split long text to each input 
      based on space -->

    work pork dork bark crack shame
    <br />
    <input  />

    <input  />

    <input  />
    <input  />
    <input  />
    <input  />
  </body>
  <script>
    // A $( document ).ready() block.
    $(document).ready(function () {});
  </script>
</html>

CodePudding user response:

  1. Split your input text based upon space.
  2. Loop between them to get each word on text box.

Example:

$(".input").keyup(function() {
  var arr = $(this).val().split(" ");
  $.each(arr, function(index, value) {
    $('input').eq(index).val(value)
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
work pork dork bark crack shame

<input  />
<input  />
<input  />
<input  />
<input  />
<input  />

CodePudding user response:

Set up a "paste" handler on the first input field. It splits the string value into an array, then cycles through the other input fields and updates their values with the next array element.

// A $( document ).ready() block.
$(document).ready(function () {
    $('input:first-of-type').on('paste', function() {
        let words = $(this).val().split(/\s /);
        $('input:not(:first-of-type)').each(function(e){
            $(this).val(words[e])
        })
    });
});
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Static Template</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  </head>
  <body>
    <!-- if type this long text to first input ,
      Split long text to each input 
      based on space -->

    work pork dork bark crack shame
    <br />
    <input  />

    <input  />

    <input  />
    <input  />
    <input  />
    <input  />
  </body>
</html>

  • Related