In certain scenarios, you may want to present a lookup field on a form as if it were read-only, while still allowing scripts to programmatically set or update its value behind the scenes. Here are two methods to achieve this without disabling the field entirely, thus preserving your ability to set its value via code:
Approach 1: Hide the Original Field and Use a Read-Only Text Field
- Retrieve the selected text from the lookup.
- Hide the original lookup control.
- Insert a new text input, marked as
readonly
, and populate it with the selected text.
$(document).ready(function()
{
// Approach 1: Replace the original field with a readonly text display
var selectedText = $('#your_lookup_field_id option:selected').text();
$('#your_lookup_field_id').hide().after('<input id="your_lookup_field_readonly" type="text" class="form-control" readonly="readonly" value="' + selectedText + '">');
...
});
Sample test result:
This way, users see a read-only display of the current value, but the original field still exists on the page and can be programmatically modified as needed.
Approach 2: Apply CSS to Simulate Read-Only Behavior
- Apply CSS to the field to disable pointer events and adjust the background color.
- The field looks and behaves like a read-only field to the user, but technically it isn’t disabled. This means you can still set its value via script.
No comments:
Post a Comment