简体   繁体   中英

How To Sort Textarea Value Using Arrays Javascript

I need to sort the value of a textarea using arrays in JavaScript.

I tried this code but nothing happened:

var x = [];
x.push(myInput.value);
x.join("/n");
x = x.sort();
myOuput.value = x.toString();

My HTML code:

<textarea id="input"></textarea>
<p>
<textarea id="output"></textarea>
<p>
<button id="button">Click</button>
<p>
<div id="test"></div>

<script src="main.js"></script>

Edit: Thank you: All the answers were helpful to me and this is my code now:

var z = myInput.value.split('\n');
z = z.sort();
myOuput.value = z.join('\n');

split the string into an array, sort it, then join it back together:

var textarea = document.getElementById('theTextareaId'); // or whatever...
textarea.value = textarea.value.split('\n').sort().join('\n');

You could take the value, split it by new line, sort it, join it with new line and assign the value back.

 function sort(t) { t.value = t.value.split('\n').sort().join('\n'); }
 <textarea onchange="sort(this)" rows="10"></textarea>

When you call the .join() method of an array, it returns a string. Your code does not capture that return value, so the joined result is immediately thrown out.

Additionally, you don't want to put the entire textarea value into the array. Instead, you need to split that string (where there are new lines), which returns an array. Then, you can sort that array.

 var ta = document.querySelector("textarea"); var btn = document.querySelector("input[type=button]"); var output = document.querySelector("div"); btn.addEventListener("click", function(){ var x = ta.value.split(/\n+/); // Split up input into an array x = x.sort(); // Sort results output.innerHTML = x.join("<br>"); // Display sorted output on new lines });
 textarea { height:7em; }
 <textarea>zx c a zz k</textarea> <input type="button" value="Sort"> <div></div>

Using the HTML included, it appears that you'd like to move the sorted list over to the output textarea. If this is the case, try:

<textarea id="input">Lorem
Foo
Ipsum
Bar</textarea>
<p>
<textarea id="output"></textarea>
<p>
<button id="button" onClick="sortInput()">Click</button>
<p>
<div id="test"></div>

Your Javascript:

function sortInput(){
  var inputField = document.getElementById('input');
  var outputField = document.getElementById('output');

  var lineArray = inputField.value.split('\n'); //create array of strings
  lineArray.sort(); //sort the array
  outputField.value = lineArray.join('\n'); //join it together in the output
}

edit: You'll likely want to more clearly define your.sort() method since the default is not very robust. It doesn't sort necessarily as you would expect with capitalization. documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM