Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behaviour when input element switches type to hidden

I discovered a strange behavior of input text/hidden elements and I would like to know why this happens.

I have an input text box that has a value, let's say "test". I delete the input element value and I change the type of this element into "hidden". If now I switch it back to "text" the original value is there! If you don't fully delete the value of the text element but change it your changes are preserved. Why if you clear the element value this change is not preserved?

I created a fiddle that can show you what I mean.

function toggler() {
  var iobj = document.getElementById('test');
  if (iobj.type == 'text') {
    iobj.type = 'hidden';
  } else {
    iobj.type = 'text';
  }
}
<button name="toggle" type="button" onclick="toggler()">Toggle</button><br /><br />
<input type="text" name="test" id="test" value="sample" />
like image 630
Elxis Avatar asked Sep 09 '18 19:09

Elxis


1 Answers

This has something to do with how different browsers handle defaultValue property of the inputs, whenever their type is changed. In this case, when the input type is changed and the .value is empty, Firefox uses the last non-empty value as .defaultValue property of the input. When the type is changed into text, Firefox uses the .defaultValue property for setting current .value property of the input. Chrome doesn't do this, i.e. it uses the last value, empty or non-empty, as the .defaultValue.

Here is a demo on jsfiddle. Comparing the logged values on Firefox and Chrome console, should demonstrate the different behaviors.

I should also mention that according to my experience/knowledge, Firefox is more standards-compliant than other browsers.

That being said, changing type of an input has never been a good idea. Form elements are very different and browsers handle the case in different ways.

like image 67
undefined Avatar answered Nov 20 '22 10:11

undefined