简体   繁体   中英

How do I use jquery/javascript to turn textarea contents into an array?

I have a textarea where users can enter text separated by commas. I want to take the contents of this field and turn it into an array, where each element in the array comes from the data in the textarea field. For example, if a user enters "value_1, value_2, value_3" into the textarea field, then I want to turn this into an array where element 1 is "value_1, element 2 is "value_2", and element_3 is "value 3". I thought I had this figured out, but for some reason the array only ends up containing one element (the first element in the array, but not the other elements). Here is my code:

<script>
    var resultsArray = new Array();
    var content = $("textarea[name=my_content]").val();
    var results = content.split(',');
    var num = results.length;
    for(var i = 0; i < num; i++) {
        resultsArray.push(results[i]);
    };

    $.ajax({
        type: "POST",
        url: 'my/url',
        dataType: 'html',
        data: {results:resultsArray},
        success: function(){}
    });
    return false;
</script>

I know my server-side script is working because everything works fine if I hard-code my script like this:

<script>
    var resultsArray = new Array("value_1", "value_2", "value_3");
    $.ajax({
        type: "POST",
        url: 'my/url',
        dataType: 'html',
        data: {results:resultsArray},
        success: function(){}
    });
    return false;
</script>

It turns out that there was a newline character that showed up in some of the values. Everything worked once I stripped away the newline characters.

just use this it really makes everything simple....

content.split(/\\s*,\\s*/); Updated This works perfectly.

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