2011-07-08 51 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);'但是當你搜索字符爲/,[,], - 等我的答案的當前代碼沒有這個問題 –