我在用jquery在文本框中键入内容时尝试替换textarea中的字符串值。我使用按键事件来尝试实现这一点。此fiddle中的这里可能是什么问题?
<input type="text" id="textbox" />
<textarea id="txtArea">This is a sample test.</textarea>
jQuery代码
$("#textbox").keypress(function () {
var txtAreaValue = $('#txtArea').val();
var txtAreaValueAfterreplace = txtAreaValue.replace('sample', $(this).val());
$('#txtArea').val(txtAreaValueAfterreplace);
});
最佳答案
主要问题在于,使用按键时,您会在设置输入框之前获得其值,因此什么也不会出现。但是,即使将其更改为keyup
,您也仍然只会获得一个值,因为一旦替换了“样本”,它就会消失,因此无法再次替换。
如果要用textarea的完整值替换sample,则需要考虑一种新的逻辑。考虑以下示例:
$("#add").click( function () {
$( '#txtArea' ).val( $('#txtArea').val().replace( 'sample', $("#textbox").val() ) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textbox" /><br>
<input type='button' id='add' value='add'>
<textarea id="txtArea">This is a sample test.</textarea>
或者当用户停止输入时我们替换
var typing;
$("#textbox").keyup( function () {
// Stop the change from being made since they typed again
clearTimeout(typing);
// They typed, so set the change to queue up in a 3rd of a second
typing = setTimeout(function(){
$( '#txtArea' ).val( $('#txtArea').val().replace( 'sample', $("#textbox").val() ) );
},350);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textbox" /><br>
<textarea id="txtArea">This is a sample test.</textarea>