I have a Bootstrap 3 prepended text field with a checkbox. I want the field to be disabled until the checkbox is true, and then I want to not only enable it but set focus to it
I used the following code and the enable/disable works great, but not sure how to set the focus...
I will likely write a directive, but I was wondering if there was some very simple way to do it as there was for the disable/enable
<div class="input-group">
<span class="input-group-addon">
<input type="checkbox" name="cbprepend" ng-model="cbprepend">
</span>
<input type="text" id="cbprependfield" class="form-control" ng-disabled="!cbprepend">
</div>
Your approach using a directive is good, but lacks some "angularity".
Here is another possible solution. First, create the directive:
.directive('checkableInput', function() {
return {
restrict: 'E',
templateUrl: 'your/template/dir/checkable-input.html',
scope: {
id: "@",
model: "="
},
link: function (scope, element, attrs) {
var input = element.find('#' + scope.id);
scope.toggleFocus = function() {
if(scope.model) {
input.focus();
} else {
input.blur();
}
}
}
};
});
The template specified in templateUrl
looks like this:
<div class="input-group">
<span class="input-group-addon" >
<input type="checkbox" ng-model="model" ng-change="toggleFocus()">
</span>
<input type="text" ng-id="id" class="form-control" ng-enabled="model">
</div>
This is how you use it:
<checkable-input id="cbprependfield" model="cbprepend" />
OK, I did use a Directive, not sure if this is the cleanest way, please give me some criticism...
.directive('pcb', function() {
return {
restrict: 'A',
link: function postLink(scope, element, attrs) {
element.on({
change: function(e) {
if (element.is(':checked')) {
element.closest('.input-group').find('.focus-target').removeAttr('disabled')
element.closest('.input-group').find('.focus-target').focus();
} else {
element.closest('.input-group').find('.focus-target').attr('disabled', 'disabled');
element.closest('.input-group').find('.focus-target').blur();
}
}
});
}
};
});
with the html
<div class="input-group">
<span class="input-group-addon" >
<input type="checkbox" pcb ng-model="cbprepend">
</span>
<input type="text" id="cbprependfield" class="form-control focus-target" disabled>
</div>