Paste multiline text in input type text (not textarea)

此生再无相见时 提交于 2019-12-03 15:52:44
Diego

I built a plugin to replace the input for a <textarea>. Here it is:

// Debe llamarse al plugin antes de construir cualquier referencia al elemento.
// El nuevo elemento debe seleccionarse por id, por name o por clases.
// En el momento de llamar al plugin el elemento debe estar visible.

// Translate:
// The plugin must be called before saving any reference to the element.
// The new element must be selected by its id, name or classes, not by the tag "input".
// When the plugin is called the element must be visible.

$.fn.acceptMultiline = function() {
  var txt = $(this),
    txtArea = $("<textarea></textarea>");

  if (txt.attr("style") != undefined)
    txtArea.attr("style", txt.attr("style"));

  if (txt.attr("class") != undefined)
    txtArea.attr("class", txt.attr("class"));

  if (txt.attr("name") != undefined)
    txtArea.attr("name", txt.attr("name"));

  if (txt.attr("id") != undefined)
    txtArea.attr("id", txt.attr("id"));

  txtArea
    .width(txt.width())
    .height(txt.height())
    .css("resize", "none");

  txt.after(txtArea)
    .remove();

  txtArea.on("input", function() {
    txtArea.val(txtArea.val().replace(/\r\n/g, " ").replace(/\r/g, " ").replace(/\n/g, " "));
  });
};

$(":text").acceptMultiline();

$("button").on("click", function() {
  $(".txt").val($(".txt").val() + "pepe");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input type="text" style="width: 700px;" class="txt" />
<button>Change value of txt</button>

View on JSFiddle

Convert the string to one line by remove the line breaks.

"multiline\ntext\nline3".split('\n').join('');
Chuck

Check this SO thread. It links to a jsfiddle that has code that i think will handle your problem

Is it possible to get pasted text without using the setTimeout() function?

The link to the jsfiddle http://jsfiddle.net/pxfunc/KDLjf/

You can use below workaround for IE. Please read the comment in the code sample -

    jQuery("input").bind("paste", function() {
        var element = jQuery(this);
        setTimeout(function () {
            var text = element.val();
// window.clipboardData works only in IE.
//  For other browsers, element.val() should work
            if(window.clipboardData){
              text = window.clipboardData.getData('Text');
            }
                matches = text.match(/[^0-9]+/g);
            if (matches != null) {
                for (var i = 0; i < matches.length; i++) {
                    text = text.replace(matches[i], ((matches[i].indexOf("-") < 0) ? "," : "-"));
                }
                element.val(text);
            }
        }, 100);
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!