2016-10-20 49 views
0

我不知道爲什麼代碼在第二個if循環不起作用。它應該檢查「[」字符的文本區域字符串並將其替換。jquery不會替換textarea中的文本

$(function() { 
    $('#form').on('submit',function(){ 
    if ($('#pzad').is(':checked')){ 
    var text = $('#mytextarea').val(); 
    if (text.indexOf('[')>-1 || text.indexOf(']')>-1){ 
     $('#mytextarea').val().replace('[',''); 
     $('#mytextarea').val().replace('[',''); 
    } 
    $('#mytextarea').val('['+$('#mytextarea').val()+']'); 
    }}); 
}); 
+0

這是工作,只是不同的比你想象的。替換不會改變原始字符串,但_returns_已更改的值,因此您需要使用該返回值執行某些操作。 – CBroe

回答

2

由於.replace()返回新的字符串,你需要更新textarea文本。

var newstr = $('#mytextarea').val().replace('[',''); 
$('#mytextarea').val(newstr); 

您可以使用.val(fn)

$('#mytextarea').val(function(_,currentValue){ 
    return currentValue.replace('[',''); 
});