2011-07-08 52 views
0

我在我的页面中有此代码。有两个文本框和一个textarea。使用jquery或javascript

<fieldset> 
    <legend><b>Search Criteria</b></legend> 
    <table> 
     <tr> 
      <td>     
       Find Text: 
       <input type="text" style="width:150px" id="txtFind"/> 
       <input type="button" id="btnfind" value=" Find "/>       
      </td> 
     </tr> 
     <tr> 
      <td> 
       Replace Text: 
       <input type="text" style="width:150px" id="Text1"/> 
       <input type="button" value="Replace Text" id="btnReplace"/> 
      </td> 
     </tr> 
    </table> 
</fieldset> 
<br /> 
<fieldset> 
    <legend><b>Result</b></legend> 
    <table> 
     <tr> 
      <td>  
       <%:Html.TextArea("Hello ASP.NET here")%> 
      </td> 
     </tr> 
    </table> 
</fieldset> 
在我的第一个文本框

,如果我输入“这里”然后我点击查找按钮,它应该找到文本

,如果我进入的第二个文本框“MVC”点击替换文本按钮它应该替换文本“这里”到“MVC”(“您好ASP.NET MVC”),

请问任何人可以帮我吗?如何使用JavaScript或jQuery来做到这一点?

感谢

+2

所以,你想要的文字区域为 “你好ASP.NET MVC” 呢?你的要求很不明确。 –

+0

Marc谢谢你的回应。我的问题是我从表中textarea显示文本。所以当我想在textare中找到一些文本时,我只需在查找文本框中输入该文本,然后在第二个文本框中输入替换文本,如果单击替换文本按钮,则应该用替换文本替换查找文本。 – Sandy

回答

1

这应该让你开始:http://jsfiddle.net/DD7t5/

使用jQuery和highlight jQuery plugin

var $result = $('#result'), 
    $txtFind = $('#txtFind'), 
    $txtReplace = $('#txtReplace'); 

$('#btnFind').click(function() { 
    $result.removeHighlight(); 

    var findValue = $txtFind.val(); 

    if (findValue.length > 0) { 
     $result.highlight(findValue) // find and highlight 
    } 
}); 

$('#btnReplace').click(function() { 
    $result.text($result.text().replace(eval('/' + $txtFind.val() + '/gi'), 
     $txtReplace.val())); // replace 
}); 
+0

真棒它是gr8 ..感谢您的回应.. – Sandy

2

Asuming您的textarea有id="textarea",你应该这样做:

$("#btnfind").click(function(){ 
    var find = $("#txtFind").val(); 
    var replace = $("Text1").val(); 
    var text = $("#textarea").val(); 
    while(text.indexOf(find) >= 0){ 
     text = text.replace(find, replace); 
    } 
    $("#textarea").val(text); 
}); 

(请注意,我们不使用正则表达式来代替,因为查找的文字是动态的,因此我们必须逃避“查找”文本)。

希望这会有所帮助。干杯

+0

谢谢埃德加,你能告诉我如何处理正则表达式?因为找到我需要用某种颜色突出显示的元素? – Sandy

+0

我需要找到并替换我的文本框中的多个地方的文字。 – Sandy

+0

不客气,桑迪。我的答案的代码替换搜索到的字符串的所有出现。 但是,使用正则表达式,而不是整个**'while'阻塞它将会是:'text = text.replace(new Regexp(find,“g”),replace);'但是当你搜索字符为/,[,], - 等我的答案的当前代码没有这个问题 –