Skip to content

Instantly share code, notes, and snippets.

@Manc
Last active August 29, 2015 13:56
Show Gist options
  • Save Manc/8937240 to your computer and use it in GitHub Desktop.
Save Manc/8937240 to your computer and use it in GitHub Desktop.
jQuery extension to prevent line breaks in textareas. Demo: http://jsfiddle.net/nicz/Z77YQ/1/
/**
* Disallow line breaks in textareas. Line breaks are converted to
* a space character or any other replacement.
* Usage examples:
* // Convert line breaks only once to spaces (default):
* $('textarea').nolinebreaks();
*
* // Convert line breaks only once to something else:
* $('textarea').nolinebreaks(' / ');
*
* // Convert line breaks once and on any change:
* $('textarea').bind('keyup change', function() { $(this).nolinebreaks(); }).trigger('change');
*/
(function($) {
$.fn.nolinebreaks = function(replacement) {
replacement = (typeof replacement === 'undefined') ? ' ' : replacement;
var $textarea = this,
value = $textarea.val(),
end = value.substring(value.length - replacement.length - 1, value.length - 1),
newValue = value.replace(/\n+/g, end === replacement ? '' : replacement);
if (value !== newValue) {
$textarea.val(newValue);
}
return this;
};
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment