I would love to display text inputs, but they should break if the text is too long. But the user should not be able to insert new lines by himself The reason for that is that I always want to have it’s whole value visible.
I think that there is no solution with CSS, which would be best, so I decided to replace all input elements with textarea elements and automatically adjust it’s height. To prevent multiple lines I simply replace them.
I did it with this code, but especially the part where I grab all the input’s attributes to convey them to the texarea seems awkward to me.
$(document).ready(function(){
$('input[type="text"]').each(function(){
var attrs = { rows: 1 }, defaults = ['name', 'id', 'title', 'value', 'class', 'style', 'disabled', 'readonly', 'accesskey'];
for(var i in defaults){
if($(this).is(':[' + defaults[i] + ']')){
attrs[defaults[i]] = $(this).attr(defaults[i]);
}
}
attrs["class"] = (attrs["class"] || "") + " text-input";
$(this).replaceWith($('<textarea />', attrs).change(function(){
$(this).val(function(i, v){
return v.replace(/\n/g, " ");
}).css("height", $(this).attr("scrollHeight"));
}));
});
});
Do you know any improvements?
I’d be tempted to use a
<textarea>and add js w/ jQuery to return false if a keypress was ‘enter’. I think it’s a bit lighter weight. E.g.Admittedly, it’s not fool-proof, but you can add code to scrub the contents of the textarea when its value changes.