Reputation: 3132
One quick question i am trying to auto-size the input text fields according to user inputs and i have some problems with the dynamically created input text ones, instead the others are functioning.
Here is the javascript , i am using:
<script>
(function($){
$.fn.autoGrowInput = function(o) {
o = $.extend({
maxWidth: 1000,
minWidth: 0,
comfortZone: 70
}, o);
this.filter('input:text').each(function(){
var minWidth = o.minWidth || $(this).width(),
val = '',
input = $(this),
testSubject = $('<tester/>').css({
position: 'absolute',
top: -9999,
left: -9999,
width: 'auto',
fontSize: input.css('fontSize'),
fontFamily: input.css('fontFamily'),
fontWeight: input.css('fontWeight'),
letterSpacing: input.css('letterSpacing'),
whiteSpace: 'nowrap'
}),
check = function() {
if (val === (val = input.val())) {return;}
// Enter new content into testSubject
var escaped = val.replace(/&/g, '&').replace(/\s/g,' ').replace(/</g, '<').replace(/>/g, '>');
testSubject.html(escaped);
// Calculate new width + whether to change
var testerWidth = testSubject.width(),
newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth,
currentWidth = input.width(),
isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth)
|| (newWidth > minWidth && newWidth < o.maxWidth);
// Animate width
if (isValidWidthChange) {
input.width(newWidth);
}
};
testSubject.insertAfter(input);
$(this).bind('keyup keydown blur update', check);
});
return this;
};
})(jQuery);
$('input').autoGrowInput();
</script>
this is how i create the text input fields :
var tracktitleinput = document.createElement('input');
tracktitleinput.setAttribute('type', "text");
tracktitleinput.setAttribute('name', "tracktitle");
tracktitleinput.setAttribute("required", true);
tracktitleinput.setAttribute("placeholder",
"Required Field");
tracktitleinput.setAttribute("class", "required");
and it does works perfectly with this ones :
<input type="text" id="releasename" name="releasename" required="true" placeholder="Required Field" />
Upvotes: 0
Views: 401
Reputation: 27012
When you create new inputs, you need to call the autoGrowInput()
function for those elements:
var $newInput = $('<input/>', {
type : 'text',
name : 'tracktitle',
required : 'true',
placeholder : 'Required Field',
class : 'required'
}).autoGrowInput();
Upvotes: 1
Reputation: 38345
If they don't exist when you call $('input').autoGrowInput();
I'm not sure why you'd expect them to have that functionality attached to them. jQuery isn't magic, it doesn't automatically know that code you ran when the page loaded is supposed to apply to elements that didn't exist then, unless you explicitly tell it to (and that only works for events via event delegation).
You'll need to call your plugin again when creating the dynamically added elements:
$(tracktitleinput).autoGrowInput();
Upvotes: 0