在 input 输入框中有逗号自动替换换行符

背景

有一个业务场景, 将 excel 中的多列数据复制到 input 文本框中 , 需要将换行符替换成逗号(,) , 便于后台系统批量查询。

由于在粘贴数据到 input 中时,换行符会被删除,无法读取输入值的原始版本,导致无法实现此功能。

解决方案

jquery

$(function(){
    $('input').on('paste', function(e){
        var target = $(e.target);
        var textArea = $("<textarea></textarea>");
        textArea.bind("blur", function(e) {
            target.val(textArea.val().replace(/\r?\n/g, ', ') );
            textArea.remove();
        });
        $("body").append(textArea);
        textArea.focus();
        setTimeout(function(){
            target.focus();
        }, 10);
    });
});

react 版本

核心代码 :

  handlePaste(e: any) {
        if (!this.props.enableNewLineSeparate) {
              return;
        }
        let that = this;

        let target = e.target;
        let separator = that.props.newLineSeparator;
        const textArea = document.createElement('textarea')
        // 触发 forcus 事件,需要设置透明度为0; 如果设置 display:none ,无法触发事件
        textArea.style.opacity = '0';
        textArea.style.position = 'absolute';
        textArea.onblur = function (e: any) {
              let val = e.target.value;
              val = reactHelper.trimEnd(val, '\r\n')
              val = reactHelper.trimEnd(val, '\n')
              let n_val: string = val.replace(/\r?\n/g, separator);
              that.setValue(n_val)
              textArea.remove();
        }
        var parent = that.inputRef.parentNode;
        parent.appendChild(textArea)
        textArea.focus();
        setTimeout(function () {
              target.focus();
        }, 10);

  }

————————————————
原文链接:https://stackoverflow.com/questions/8975918/how-to-replace-newline-with-comma-in-input-using-jquery

posted on 2022-11-16 12:45  爱上键盘的蜗牛  阅读(834)  评论(0编辑  收藏  举报

导航