Forum Moderators: open

Message Too Old, No Replies

how to dynamically change an element's type?

trying to change textbox to textarea with event

         

chrisdr

6:54 pm on Mar 29, 2007 (gmt 0)

10+ Year Member



I found the following code in another forum but i can't get it to work for me... Any input would be appreciated.

function changeTextBox2TextArea(elementId)
{
var _el = document.getElementById(elementId);
var _parent = _el.parentNode;

// we remove the element from the DOM (optional as seen below...)
_parent.removeChild( _el );

// property is read-only so we replace the element
if ( _el.type == 'text' ) {

// IE doesn't like too much playing with DOM, so we use the innerHTML method.
// Using innerHTML, replace all current elements inside _parent with the new
// elements specified in the string.
_parent.innerHTML = '<textarea id="' + _el.id + '">' +
_el.value + '</textarea>';

} else {
_parent.innerHTML = '<input type="text" id="' +
_el.id + '" value="' + _el.value + '" />'; }

_el = null; // remove any reference to the old element
}

<input type="button" value="Change Text Box"
onclick="changeTextBox2TextArea('test');" />

<div>
<input type="text" id="test" />
</div>

RonPK

2:17 pm on Mar 30, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I tested it with IE7: no problems. All I had to do was put the javascript inside <script> tags.

chrisdr

4:54 pm on Mar 30, 2007 (gmt 0)

10+ Year Member



I'm using IE 6, I wonder if that's an issue...

all i get when i click the button is a very generic IE error message:

Line:30
Char:1
Error:Object Expected
Code:0
URL:....

Oh well, I have a workaround anyway... thanks

Dabrowski

8:37 pm on Mar 31, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I believe the object it's expecting IS changeTextBox2TextArea.

As RonPK said it's probably 'cos you missed the SCRIPT tags. IE7 is probably smart enough to realise this.

I always wondered why if you get an error 'expected )' or similar, why doesn't it just add it? It obviously knows where it's supposed to go or it would be complaining!