How to make a text-box partially readonly using angularjs/HTML attribue? For example, a textbox having default value say "+91",which is readonly and else part need to enter values.
Definition and UsageA read-only input field cannot be modified (however, a user can tab to it, highlight it, and copy the text from it). The readonly attribute can be set to keep a user from changing the value until some other conditions have been met (like selecting a checkbox, etc.).
You can make the TextBox as read-only by setting the readonly attribute to the input element.
HTML
<input id="field" type="text" value="+91" size="50" />
<div id="output">
</div>
Javascript
var readOnlyLength = $('#field').val().length;
$('#output').text(readOnlyLength);
$('#field').on('keypress, keydown', function(event) {
var $field = $(this);
$('#output').text(event.which + '-' + this.selectionStart);
if ((event.which != 37 && (event.which != 39))
&& ((this.selectionStart < readOnlyLength)
|| ((this.selectionStart == readOnlyLength) && (event.which == 8)))) {
return false;
}
});
Demo http://jsfiddle.net/Yt72H/
Based on Nitin's work above I created this Angular Directive that should do the trick
JSFiddle
http://jsfiddle.net/codemonkeytony/3ew5h6bf/7/
Angular
var partialApp = angular.module("partialApp", []);
partialApp.directive('partialReadonly', function () {
return {
restrict: 'A',
link: function (scope, elem, attrs) {
elem.on('keypress, keydown', function (event) {
var readOnlyLength = attrs["partialReadonly"].length;
if ((event.which != 37 && (event.which != 39))
&& ((elem[0].selectionStart < readOnlyLength)
|| ((elem[0].selectionStart == readOnlyLength) && (event.which == 8)))) {
event.preventDefault();
}
});
$(window).load(function () {
elem[0].value = attrs["partialReadonly"];
});
}
};
});
HTML
<input type="text" partial-readonly="Readonly text goes here" />
Hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With