<input>
When someone pastes multi-line text into the input, I need the newlines (\r, \n, and \r\n) and tabs \t replaced with a comma ,. Most of the time, the input will be coming from Microsoft Excel or Apple Numbers when a user copies a column or a row.
$(function(){
// jQuery paste event. how trendy!
$('input').on('paste', function(e){
var e = $(this);
setTimeout(function(){
e.val( $.trim(e.val()).replace(/\s+/g, ',') );
}, 0);
});
});
Some cells in their spreadsheet might have spaces in them so /\s+/g is going to be too broad. However, /[\r\n\t]+/g isn't working. In fact, I don't think jQuery even has access to the input's value before the newlines are being removed.
I've provided a jsfiddle with expected inputs and outputs
<!-- sample input, copy below this line --
one
2
hello world
foo bar
m3000
-- end copy -->
<!-- output should look like
one, 2, hello world, foo bar, m3000
-->
You can redirect the event to a textarea and then get the paste value which will content the \n characters:
$(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);
});
});
You can try it here: http://jsfiddle.net/dE3At/
I am afraid this is not possible (without hacking around).
onpaste event (IE has the proprietary clipboardData.getData(), but there is no not-hacky cross-browser way).I suggest you use a textarea, so you can maintain those newlines and do whatever you want to them. You can style the textarea to look like an input, disable resizing and make it have only one row.
jsFiddle Demo with textarea
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With