0

我有一个搜索框和一个建议框来显示建议。

一旦用户在搜索框中输入内容,就会出现建议,然后用户可以选择要添加到搜索输入框中的建议之一。之后,用户将能够输入其他术语以接收建议等。

我可以显示建议并将所选建议添加到输入框中,但是

假设用户输入 f 然后首先被建议并且用户选择它,那么输入框将是 f,first 但它应该是 first。如果我重置输入,我将丢失其他搜索词。

简而言之:我想保留最后一个分号之前的所有值并删除分号之后的所有值。

代码

<script type="text/javascript">
    function selectS(value){
        alert("clicked:" + value);
         var curr = $('#term').val();
            if(curr)
                 curr += ";";
            $('#term').val(curr + value);
    }
....

<s:form id="searchForm" method="POST" enctype="multipart/form-data">
     <s:textfield id="term" name="term" label="Search" onkeyup="find(this.value)"/>
</s:form>
4

2 回答 2

2

I think what you want is Auto Complete from Javascript UI

See http://jqueryui.com/autocomplete/#multiple ...

it allows multiple select in search box.

if for some reason you dont want to use it.. you can use below code

 function split( val ) {
      return val.split( /;\s*/ );
    }

function selectS(value){
        alert("clicked:" + value);
         var curr = split($('#term').val());
         // remove the current input
          curr.pop();          
          // add the selected item
          curr.push( value );
         // add placeholder to get the comma-and-space at the end
          curr.push( "" );

         $('#term').val(curr.join( "; " ););
    }
于 2013-05-14T04:42:21.973 回答
0

Learn basic regular expressions.

var text = "foo";
var str = "asdf;qwerty;g";
var newStr = str.replace(/(;)?[^;]+$/,"$1" + text);
console.log(newStr);

Same thing could be done with split and join

var text = "foo";
var str = "asdf;qwerty;g";
var parts = str.split(";");
parts.pop();
parts.push(text);
var newStr = parts.join(";");
console.log(newStr);
于 2013-05-14T04:48:04.147 回答