繁体   English   中英

Textarea通过多个输入值实时更新

[英]Textarea realtime update by multiple input values

这是我的表单示例:

<form action="" method="POST">
    <input type="text" name="firstTarget" />
    <input type="text" name="secondTarget" />
    <input type="text" name="thirdTarget" />
    <textarea name="result">I have this text and I want to update it using firstTarget. After that I want to use secondTarget and thirdTarget</textarea>
</form>

我想通过将firstTarget,secondTarget和thirdTarget替换为firstTarget,secondTarget和thirdTarget输入中的实际值来实时更新我的​​textarea值。

HTML:

<form action="" method="POST">
    <input type="text" name="firstTarget" onblur="tst(this);" />
    <input type="text" name="secondTarget" onblur="tst(this);" />
    <input type="text" name="thirdTarget" onblur="tst(this);" />
    <textarea style="width:500px; height: 100px;" name="result">I have this text and I want to update it using firstTarget. After that I want to use secondTarget and thirdTarget</textarea>
</form>

和javascript:

function tst(elm){
    var trgt=document.getElementsByTagName('textarea')[0];
    trgt.value=trgt.value.replace(elm.getAttribute('name'), elm.value);
}

在这里工作jsfiddle演示

编辑:
如果您想更新您的针一样的multple实例firstTarget ,那么你需要动态创建的正则表达式,所以你可以通过它的全球标志。

function tst(elm){
    var trgt=document.getElementsByTagName('textarea')[0];
    trgt.value=trgt.value.replace(RegExp(elm.getAttribute('name'), 'g'), elm.value);
}

在这里工作jsfiddle演示

你可以这样做:

/* cache original value so we keep the keywords*/
var txt=$('textarea').val();


$('input').keyup(function(){
   var newText=txt;
    newText=newText.replace( this.name, this.value);    
    $('textarea').val(newText);    
});

然而,一个问题是如果textarea没有设置为只读,并且用户更改其中的任何内容,则这将无法工作,因为它依赖于存储原始值并更改它。 需要了解有关此设置的用例的更多信息,以帮助进一步推进它。

如果用户触摸任何关键字都将失败,则其他解决方案中也存在相同的问题

DEMO

这是一个将输入值存储在每个键盘上的解决方案,因此用户也可以编辑textarea。

$('input').keyup(function(){
    /* value to be replaced is stored in data object*/
    var regVal=$(this).data('replace');    
   var newText=$('textarea').val().replace( regVal, this.value); 
    /* store value that will get replaced*/  
    $(this).data('replace', this.value)     
    $('textarea').val(newText);    
}).each(function(){
    /* on page load set initial replacement value as name of input*/
    $(this).data('replace', this.name); 
});

唯一的限制是它假定用户没有重复的条目

DEMO

您可以使用此代码执行此操作:

$('firstTarget').onChange(function(){
      var str =  $('result').val();
      str.replace(firstTarger, $( this ).attr('name'));
      $('result').text(str);
 }):

 $('secondTarget').onChange(function(){
      var str =  $('result').val();
      str.replace(firstTarger, $( this ).attr('name'));
      $('result').text(str);
 }):

$('thirdTarget').onChange(function(){
      var str =  $('result').val();
      str.replace(firstTarger, $( this ).attr('name'));
      $('result').text(str);
 }):

请享用!!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM