Javascript how do rearrange or sort text inside text box

Discussion in 'JavaScript' started by die4once, Sep 17, 2009.

  1. #1
    How do rearrange or sort text inside a text box

    e.g "test test2"

    I want to make "test2" at the front of the text box the page is submited or unloaded or whatever

    Im n00b
     
    die4once, Sep 17, 2009 IP
  2. die4once

    die4once Peon

    Messages:
    16
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    or a button
     
    die4once, Sep 17, 2009 IP
  3. Jaguarjace

    Jaguarjace Guest

    Messages:
    52
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Do you mean something like this:
    
    <textarea id="box" cols="40" rows="5">
    test test2
    </textarea>
    <br>
    <input type="button" value="Swap Around!" onclick="document.getElementById('box').value='test2 test'">
    
    Code (markup):
    When you click the button, it finds the element's id and changes the value to whatever you want it to be. :)[/B]
     
    Jaguarjace, Oct 6, 2009 IP
  4. camjohnson95

    camjohnson95 Active Member

    Messages:
    737
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    60
    #4
    Do you know any javascript?
    1. Use the split function to split the value of the textbox using a space(" ") as the splitter, and store in an array.
    2. You can then sort the array accordingly, it depends on how you want it sorted. Alphabetically is easy (just use the sort() method.
    3. Clear the textbox and write the array back into it, using the join method to do this.
     
    camjohnson95, Oct 6, 2009 IP
  5. camjohnson95

    camjohnson95 Active Member

    Messages:
    737
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    60
    #5
    something like:
    
    document.getElementById("submitButton").onclick = function() {
        var myTextbox = document.getElementById("myTextbox");
        var myArray;
        myArray = myTextbox.value.split(" ");
        myArray.sort();
        myTextbox.value = myArray.join(" ");
        return true;
    }
    
    Code (markup):
    Where 'submitButton' is the ID of the button. And myTextbox is the ID of the textbox(or textarea).
     
    camjohnson95, Oct 6, 2009 IP