Last active
August 29, 2015 13:56
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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