簡體   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