簡體   English   中英

使用javascript從文本和textarea字段中創建標簽

[英]Make tags from text and textarea fields content with javascript

有沒有一種方法可以從文本字段,textarea字段和一些自定義文本中選擇內容,合並所有內容,並自動更新具有該內容但要用逗號分隔的單詞的textarea字段,如下所示:

  • 內容文本字段: Samsung tv
  • 上下文文本字段: Led Smart tv
  • 自定義文字: check the price

結果:textarea字段將自動更新:

三星,電視,LED,智能,電視,支票,價格?

我有這段代碼可以將內容從文本更新為textarea,但我不知道如何在每個單詞后加上逗號:

<script type="text/javascript">
            function update(elem) { 
                document.getElementById('textareaDescription').value = " check price for " + elem.value ;  
            }
        </script>
Text: <input type="text" onchange="update(this)">
        <br>
        Textarea auto update : <textarea name="" id="textareaDescription" cols="30" rows="10"></textarea>

variable1 +“,” + variable2 +“,” + variablenth。 這就是您要找出的嗎?

在更新功能中嘗試以下操作:

// replace
var myVal = elem.value
var regex = new RegExp(' ', 'g');
myVal = myVal.replace(regex,", ");
document.getElementById('textareaDescription').value = " check price for " + myVal ;  

您必須像下面那樣修改更新功能

        function update(elem) { 
          var tosplit = "check price for " + elem.value ;
           //Get another field value, replace anotherfieldid with your actual field
           //You can add any number of fields like this. 
            var anotherfield =  document.getElementById('anotherfieldid').value 
            tosplit =  tosplit+anotherfield; 
          var text =tosplit.split(" ");
          document.getElementById('textareaDescription').value = text ;
        }

盡管您已經接受了答案,但我還是建議您使用以下替代方法:

function updateValue(els, output){
    // creates an empty array
    var textArray = [];

    /* iterates through the `els` array and if the value is not
       an empty string, splits the value at the white-spaces
       and pushes the array of values to the `textArray` */
    for (var i=0,len=els.length; i<len; i++){
        if (els[i].value !== ''){
            textArray.push(els[i].value.split(/\s/));
        }
    }

    /* makes the value of the `output` (textarea) equal to the 
       comma-separated string of words from the inputs, and
       adds a full-stop/period to the end of the 'sentence' */
    output.value = textArray.join(',') + '.';
}

var inputs = document.getElementsByTagName('input'),
    output = document.getElementById('result'),
    els = [];

// makes an array from the `inputs` nodeList 
for (var i = 0, len = inputs.length; i<len; i++) {
    els.push(inputs[i]);
}

// assigns the function to call
for (var i = 0, len = els.length; i<len; i++) {
    els[i].onkeyup = function(e){
        updateValue(els, result);
    };
}

JS小提琴演示


編輯以解決OP留下的問題(在下面的評論中):

var inputs = document.getElementsByTagName('input')我不能通過id而不是標簽名來獲取元素?

當然可以。 關於如何收集要操作的相關元素,您有多種選擇。 在示例中,我只是將這些元素放入els變量中; 因為那已經是傳遞給函數的那個​​了(但是可以根據自己的代碼進行調整)。

首先,使用document.getElementById()

var els = [document.getElementById('one'),document.getElementById('two')];

JS Fiddle演示 (請注意,刪除了第一個for循環,該循環用於將相關節點壓入els數組)。

其次,您可以使用數組包含要操作的元素的id

/* not every browser has access to `indexOf()` for arrays, so an
   alternative is defined */

function inArray(needle,haystack) {
    // use native version if possible:
    if ([].indexOf !== undefined){
        return haystack.indexOf(needle);
    }
    // otherwise use custom approach:
    else {
        for (var i=0,len=haystack.length; i<len; i++){
            if (needle == haystack[i]){
                return i;
            }
        }
        return -1;
    }
}

var inputs = document.getElementsByTagName('input'),
    output = document.getElementById('result'),
    // array of the `id`s of the elements you want to use:
    elementIdsToUse = ['one','two'],
    els = [];

for (var i = 0, len = inputs.length; i<len; i++) {
    // if the `inputs[i]` node's `id` is in the array of `id`s...
    if (inArray(inputs[i].id,elementIdsToUse) > -1){
        // push that node to the `els` array:
        els.push(inputs[i]);
    }
}

for (var i = 0, len = els.length; i<len; i++) {
    els[i].onkeyup = function(e){
        updateValue(els, result);
    };
}

JS小提琴演示

第三,您當然可以使用類名(再次使用indexOf() ):

for (var i = 0, len = inputs.length; i<len; i++) {
    if (inputs[i].className.indexOf('useThis') > -1){
        els.push(inputs[i]);
    }
}

for (var i = 0, len = els.length; i<len; i++) {
    els[i].onkeyup = function(e){
        updateValue(els, result);
    };
}

JS小提琴演示

最后,在改變主意之后; 擴展Array原型的一種方法,以提供Array.indexOf()方法(如果當前瀏覽器中不存在):

Array.prototype.indexOf = Array.prototype.indexOf || function(needle) {
    for (var i = 0, len = this.length; i<len; i++){
        if (this[i] == needle){
            return i;
        }
    }
    return -1;
};

JS小提琴演示

這允許直接調用Array.indexOf() ,而不是(如上所述)不必在不支持的瀏覽器中不必要地使用兩個函數調用(並每次都測試其存在)來成功使用一個函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM