JavaScript - Lock a select field

From All n One's bxp software Wixi

Jump to: navigation, search

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.

if (this.value != ''){ this.readOnly = true; }

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.

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);
}

This removes all the options from the drop down list EXCEPT the desired one.