Changing the type of an already rendered HTMLInputElement
is a bit of a security and data consistency issue and many browsers (especially IE and old versions of FF) don't allow for this to happen. Which is reasonable.
That said, some browsers (looking at Chrome 83 right now) do allow on-the-fly type changes. Changing between incompatible formats (e.g. password
->number
) will clear any value. Changing anything to hidden
will remove the input element from the document flow. Etc.
If you can find any documentation on what exactly happens when transitioning between various type pairs, please edit the resource into here. Do change
events trigger? Does data get lost?
A SOLUTION
The simplest clean solution in my opinion is to create a new input[type="text"]
and insert it into the document after the hidden
input. Then, add the relevant event listeners (starting at least with keyup
and change
) onto the visible input to immediately propagate the edited value to the hidden input. Then trigger the same event on the hidden input.
This way, any code that relies on the hidden input will continue working correctly and you will have added UI to proxy the hidden input's value.
Example HTML:
<h1>Hidden Input Proxy</h1>
<input id="original_field" type="hidden" value="this is the initial value" />
Example vanilla JS (add your own error handling):
function proxyHiddenInput(inputSelector) {
const hidden = document.querySelector(inputSelector);
const proxy = document.createElement('input');
proxy.type = 'text';
proxy.value = hidden.value;
hidden.after(proxy);
function propagateValue(event) {
hidden.value = proxy.value;
hidden.dispatchEvent(new Event(event.type));
if (event.type !== 'change') {
hidden.dispatchEvent(new Event('change'));
}
}
proxy.addEventListener('keyup', propagateValue);
proxy.addEventListener('change', propagateValue);
proxy.addEventListener('blur', propagateValue);
return proxy;
}
proxyHiddenInput('#original_field');
You can make this happen a little more tersely with jQuery.
RELATED