jquery将文本框值拆分为行

jim*_*jim 9 javascript forms string jquery input

我正在做的是创建一个简单的html页面,其中有一个文本框.用户将一些输入发布到该文本框,例如

first last
first last
first last
first last
Run Code Online (Sandbox Code Playgroud)

想象一下这些是不同的名字.我想要做的是在文本框中输入输入,并将其显示在屏幕上,并按字母顺序取出重复的名称,并在其周围添加选项标签.

是)我有的

 <div id="contentdisplay"></div>
<FORM action="" method="">
     <p><LABEL for="content">Paste Code Here: </LABEL></p>
     <p><textarea id="content" cols="80" rows="40"></textarea></p>
    </FORM>



 <script type="text/javascript">
  $(document).ready(function() { 
    $('#content').change(function() {
        var test = $('#content').val();
        $("#contentdisplay").html(test);
    });     
   });
  </script>
Run Code Online (Sandbox Code Playgroud)

现在,当用户在其外部单击并将其吐出到"contentdisplay"div内的屏幕时,它会从文本框中获取值.我被困在将用户输入分成行的部分.我尝试了test.split('/ n')并将其粘贴到变量中,但是没有成功.

关于此事的我的想法

  • 在循环时,通过换行符分割表单输入,将每行放入一个数组中
  • 将数组按字母顺序排序.(在此部分中删除行前后的所有空行或空格.)
  • 我不确定删除双打.在Java中,我使用了一个集合,它自动只允许每个条目中的一个进入.
  • 使用jquery的.html()循环遍历数组进行显示并添加标签

想知道是否有人可以启发我的想法以及如何解决这个问题.谢谢!

这是近似的最终版本.感谢Erik的帮助.

以下是我为了得到它而做的事情.谢谢Erik的帮助.

<script type="text/javascript">
function process() {

entered = $('#content').val();
lines = entered.split(/\n/); 
opttext = ""; 


lines = jQuery.unique(lines);
lines.sort();

for(var i in lines) {
  opttext += "<option>" + lines[i] + "</option>";
}

$('#contentdisplay').html("<select>"+opttext+"</select>");
}

$(document).ready(function() {
    $("#content").bind('change', process);
});

</script>

<div id="contentdisplay"></div>

<FORM id="myform" action="" method="">
     <p><LABEL for="content">Paste Code Here and click anywhere on the screen: </LABEL></p>
     <p><textarea id="content" cols="40" rows="10"></textarea></p>
</FORM>
Run Code Online (Sandbox Code Playgroud)

Eri*_*rik 7

试试这个:http: //jsbin.com/okigi/3/edit (编辑:将表单标签更改为div,这样示例不会在任何地方汇总)

function process() {

    entered = $('#content').val();
    lines = entered.split(/\n/);
    opttext = ""; for(var i in lines) {
      opttext += "<option>" + lines[i] + "</option>";
    }
    $('#myform').append("<select>"+opttext+"</select>");
}

$(document).ready(function() {
    $("#process").bind('click', process);
});

<FORM id="myform" action="" method="">
     <p><LABEL for="content">Paste Code Here: </LABEL></p>
     <p><textarea id="content" cols="40" rows="10"></textarea></p>
     <button id="process">Go!</button>
</FORM>
Run Code Online (Sandbox Code Playgroud)

这不会重复,或者按照字母顺序排列,但是一旦你在数组"行"中有了这些行,你就可以自己弄清楚如何做这些事情.