Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Partially read-only textbox

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.

like image 533
Kris Avatar asked Sep 29 '14 04:09

Kris


People also ask

Is it possible to make part of text box read-only?

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.).

How to make TextBox readonly in Angular?

You can make the TextBox as read-only by setting the readonly attribute to the input element.


2 Answers

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/

like image 190
Nitin Kaushal Avatar answered Oct 05 '22 03:10

Nitin Kaushal


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

like image 43
codemonkeytony Avatar answered Oct 05 '22 03:10

codemonkeytony