Changes

JavaScript - Lock a select field

1,006 bytes added, 17:53, 11 June 2014
Created page with "In some instances it may be necessary to lock a field to stop its option being changed. This is useful if you want to lock data that has been loaded from a spreadsheet. For..."
In some instances it may be necessary to lock a field to stop its option being changed. This is useful if you want to lock data that has been loaded from a spreadsheet.


For text boxes this is relatively easy. Into the onFocus of the question simply put.
<source lang="javascript" collapse="true">
if (this.value != ''){ this.readOnly = true; }
</source>

What this does, is that when the box is clicked into to be changed, it is locked to being readOnly.



Unfortunately drop down lists (i.e. selects) are not as helpful. They don't have a readOnly attribute. We can't use the disabled tag as this stops the value being stored at all. Instead we pop the following into the onFocus box.
<source lang="javascript" collapse="true">
if (this.value != ''){
var strText = this.options[this.selectedIndex].text;
var strValue = this.value;
this.length=0;
this.options[this.length] = new Option(strText, strValue);
}
</source>
This removes all the options from the drop down list EXCEPT the desired one.
7,528
edits