Jump to content

Make input field Expand onkeyup


unemployment

Recommended Posts

I am trying to make an input area expand onkeyup but my function appears to be broken.  Happen to know the fix?  It starts to fail at current.onkeyup = current.onchange = function(e)

 

var minSize = 10; //Minimum size input can be in pixels
	var increment = 7; //Increase in size per character typed

	var inputs = document.getElementsByTagName('input');

	for(var i = 0; i < inputs.length; i++)
	{
		 var current = inputs[i];
		 if((' ' + current.className + ' ').indexOf('input_variable_width') > -1)
		 {
				current.onkeyup = current.onchange = function(e) {
					   var target = e ? e.target : window.event.srcElement;

					   target.style.width = (minSize + increment * (target.value.length-1));
				}
		 }
	}

Link to comment
https://forums.phpfreaks.com/topic/239010-make-input-field-expand-onkeyup/
Share on other sites

I would aim for something more like this:

1. Detects the class a little better (works if you also had a class like "input_variable_width2")

2. Uses .size instead of a pixel width. If not that then at least use ems.

3. Uses onkeydown (because onkeyup happens when the key is released and onchange for inputs happens onblur)

// measured in characters:
var minSize = 1;
var maxSize = 10; // a good idea to have one

var inputs = document.getElementsByTagName("input");
for (var i = 0; i 	var current = inputs[i];
if ((" " + current.className + " ").indexOf(" input_variable_width ") >= 0) { // note the spaces
	current.onkeydown = function() {
		this.size = Math.min(maxSize, Math.max(minSize, this.value.length));
	};
}
}

Untested, naturally.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.