2015-07-21 68 views
2

我在這裏做錯了什麼?JQuery在輸入文本中查找和替換textarea中的字符

我的HTML

<form name="frm"> 
    <textarea rows="10" id="uinput">some text here</textarea> 
    find 1: <input type="text" id="findbox1" value="e"> 
    replace 1: <input type="text" id="replacebox1" value="666"> 
    find 2: <input type="text" id="findbox2" value="o"> 
    replace 2: <input type="text" id="replacebox2" value="000"> 
    find 3: <input type="text" id="findbox3" value="t"> 
    replace 3: <input type="text" id="replacebox3" value="777"> 
    <button type="button" id="fnrbtn">find and replace</button> 
</form> 

我的JQuery

RegExp.escape = function(str) { 
    return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); 
}; 

$("#fnrbtn").click(function() { 
    var InputBox = $("#uInput").val(), 
    FindWhat = $('#findbox' + i).val(), 
    ReplaceWhat = $('#replacebox' + i).val(), 
    NewInputBox = '', 
    msg = ''; 
    for (i = 1; i < counter; i++) { 
    msg += "\n Textbox #" + i + ": " + $('#findbox' + i).val() + " Replace #" + i + ": " + $('#replacebox' + i).val(); 
    NewInputBox = InputBox.replace(new RegExp(RegExp.escape(FindWhat), "gi"), ReplaceWhat); 
    } 
    alert(msg); 
    $("#uInput").val(NewInputBox); 
    $('#uInput').select(); 
}); 

回答

1

FindWhatReplaceWhat被放置在for循環之外,同時我想他們一定在裏面。

而且,counter未定義。你需要在使用前初始化它。

而您的HTML包含$("#uinput"),而不是$("#uInput")在JQuery代碼中。

另外,您使用舊值InputBox運行替換,而不是上一次搜索和替換操作期間的修改值。

這裏是一個固定的代碼:

RegExp.escape = function(str) {return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');}; 
 

 
$("#fnrbtn").click(function() { 
 
var InputBox = $("#uinput").val(); // uInput > uinput 
 
msg = ''; 
 
counter = 4; 
 
for(i=1; i<counter; i++){ 
 
    FindWhat = $('#findbox' + i).val(); 
 
    ReplaceWhat = $('#replacebox' + i).val(); 
 

 
    msg += "\n Textbox #" + i + ": " + $('#findbox' + i).val() + " Replace #" + i + ": " + $('#replacebox' + i).val(); 
 
    InputBox = InputBox.replace(new RegExp(RegExp.escape(FindWhat), "gi"), ReplaceWhat); 
 
} 
 
alert(msg); 
 
$("#uinput").val(InputBox); 
 
$('#uinput').select(); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form name="frm"> 
 

 
<textarea rows="10" id="uinput">some text here</textarea> 
 

 
find 1: <input type="text" id="findbox1" value="e"> 
 

 
replace 1: <input type="text" id="replacebox1" value="666"> 
 

 
find 2: <input type="text" id="findbox2" value="o"> 
 

 
replace 2: <input type="text" id="replacebox2" value="000"> 
 

 
find 3: <input type="text" id="findbox3" value="t"> 
 

 
replace 3: <input type="text" id="replacebox3" value="777"> 
 

 
<button type="button" id="fnrbtn">find and replace</button> 
 

 
</form>

+0

這是否幫助?只是好奇,因爲我剛剛注意到你刪除的答案。 –