I have seen several posts on how to convert a string to an array using .split(), but I am curious how I would have a list re-sort it's self everytime a new string is added.
For example, I have an input box where I enter names in the format of 'First Last'. On the button click event, the input div clears, a dynamic list is generated of the names entered, and it reformats them 'Last, First'.
Every time a new name is entered, the list should resort itself alphabetically.
I would have this output div split itself on a delimiter after each name, so that the list is an indexed array of strings, but I don't have a delimiter to split on.
Here is my code so far. I know there are several things I could do to improve this but I'm looking for a very simple answer to storing these values in an array instead of a list of strings just so that they can be sorted alphabetically.
Assume all data will be entered in the format 'First Last' including capitalization.
The comment in all caps involves the 'combine' variable that needs to become an array.
var namesArr = [];//create an empty array that will hold the names
var output = document.getElementById('output');//get the output element (text area).
var name = document.getElementById('name');//get the textbox
function init(){
var nameBtn = document.getElementById('addNameBtn');//get the name button element
var clrBtn = document.getElementById('clearBtn');//get the clear button element
nameBtn.onclick = enterName;//set up your events here
clrBtn.onclick = clearNames;//set up your events here
}
function enterName(){
if(document.getElementById('name').value !==""){
var arr = document.getElementById('name').value.split(" ");
var space = ", ";
var firstname = arr[1];
var lastname = arr[0];
var outputA = [];
var combine = outputA+firstname+space+lastname+"\n";
output.value += combine//I NEED THIS OUTPUT VALUE
//TO BE STORED IN AN ARRAY
//EVERY TIME A NEW STRING IS ENTERED
//SO THAT I CAN USE .sort() on the array.
}
else{
alert("Please enter a name in the format 'First Last'");
}
if(document.getElementById('name').value !==""){
document.getElementById('name').value = "";//clear names input
}
}
function clearNames(){
document.getElementById('name').value = "";//clear names input
document.getElementById('output').value = "";//clear output input
}
init();//this will run when after the DOM loads
Thank you so much for any help or feedback.
Aucun commentaire:
Enregistrer un commentaire