简体   繁体   English

如何使用jquery / javascript将textarea内容转换为数组?

[英]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. 我有一个textarea,用户可以在其中输入用逗号分隔的文本。 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. 我想获取该字段的内容并将其转换为数组,其中数组中的每个元素都来自textarea字段中的数据。 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: 例如,如果用户在textarea字段中输入“ value_1,value_2,value_3”,那么我想将其转换为一个数组,其中元素1为“ value_1”,元素2为“ value_2”,而element_3为“ value 3”。我以为我已经弄清楚了,但是由于某种原因,数组最终只包含一个元素(数组中的第一个元素,而不包含其他元素),这是我的代码:

<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. 已更新这很完美。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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