Wednesday, April 6, 2011

Changing HTML Form Element Type with Javascript

I was looking for a solution that allow me to dynamically change the form element's type before a submission.
With following example, once the select box has been changed to a text box, you can assign any value you like to it(of course,alternative way is to create new Option with your desired value, and set the selectedIndex ).
Here's javascript function:

<form method='post'>
<select name='myselect'>
<option value='1'>Option1</option>
<option value='2'>Option2</option>
</select>
<input type='button' onclick='changeInputType(this.form.myselect, "text");'>
</form>
<script>
function changeInputType(oldObject, oType) {
var newObject = document.createElement('input');
newObject.type = oType;
if(oldObject.size) newObject.size = oldObject.size;
if(oldObject.value) newObject.value = oldObject.value;
if(oldObject.name) newObject.name = oldObject.name;
if(oldObject.id) newObject.id = oldObject.id;
if(oldObject.className) newObject.className = oldObject.className;
oldObject.parentNode.replaceChild(newObject,oldObject);
return newObject;
}
</script>


The javascript was copied from this website

No comments: