make a field disabled/read-only in SharePoint 2013 new/edit form
-
08-02-2021 - |
Question
I tried to make some fields disabled/readonly in the new/edit form in Sharepoint 2013. I want to use title only. See my code below. Only "textarea" works fine. The others don't work, still editable.
<script src="../jquery/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
/*'textare...' for multiple line text works */
$("textarea[Title='Notes']").attr("disabled", true);
/*The code below don't work, still editable on those fields*/
$("input[title='Release Info']").attr("disabled",true);
$("input[title='Release Date']").attr("disabled",true);
$("select[title='Tools']").attr("disabled",true);
});
</script>
Solution
According to .prop()
Vs .attr()
,
- You usually want
prop()
rather thanattr()
.- In the majority of cases, prop() does what
attr()
used to do. Replacing calls toattr()
withprop()
in your code will generally work.- Properties are generally simpler to deal with than attributes. An attribute value may only be a string whereas a property can be of any type. For example, the checked property is a Boolean, the style property is an object with individual properties for each style, the size property is a number.
And According to Disable/enable an input with jQuery,
For jQuery 1.6+, To change the
disabled
property you should use the.prop()
function.
So, you can try using your code like below:
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
/*'textarea...' for multiple line text works */
$("textarea[Title^='Notes']").prop("disabled", true);
$("input[Title^='Release Info']").prop("disabled", true);
$("input[Title^='Release Date']").prop("disabled", true);
$("select[Title^='Tools']").prop("disabled", true);
});
</script>
Note:
I have used Starts With(^=
) Selector which makes your element selection successful in some cases where your field is Required as in SharePoint it automatically adds Required Field
to the title
attribute of your field.
For Example:
If you have a single line of text field with display name Release Info
and this field is Required then its title
property will be like Release Info Required Field
. In such cases $("input[Title='Release Info']")
selector fails.
Reference: Attribute Starts With Selector.
Additional Reference: Difference between disabled
and readonly
.
OTHER TIPS
The below script works for me:
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script >
$(document).ready(function() {
$("textarea[Title='Notes']").attr("disabled", "disabled");
$("input[Title='Release Info']").attr("disabled","disabled");
$("input[Title='Release Date']").attr("disabled","disabled");
$("select[Title='Tools']").prop("disabled",true); }
);
</script>
Try using this:
$("input[Title='Release Info']").props("disabled","disabled");