I have this html:
<div
class="data__file"
v-for="(data, index) in paginatedData"
:key="index"
>
<label class="data__info" :for="data.idfile" #click="onClickWithShift($event, index)">
<img
:src="data.link"
alt=""
:class= "{ 'data__image' : 1 ,'data__image-active' : (data.checked === 1) }"
/>
<input
v-if="isManager === true"
type="checkbox"
class="data__access"
:value="data.idaccess"
:checked="(data.checked === 1) ? 1 : null"
v-model="checkedFilesPermission"
/>
<input
v-if="isManager === false"
type="checkbox"
class="data__access"
:value="data.idfile"
:checked="(data.checked === 1) ? 1 : null"
v-model="checkedFilesDownload"
/>
</label>
</div>
This code generate list of checkbox inputs, then I need when user click on label with shift (because input`s is display:none), all checkboxes between clicked inputs will checked or unchecked like it make with jquery here
How can I shift-select multiple checkboxes like GMail?
But I cant realise how I can get it.
Big thanks to user Spiky Chathu, I did how He said, and its work without v-model , but when I try use v-model, it doesn`t work.
also this is my data:
data() {
return {
isManager: this.$store.getters.isManager,
checkedFilesPermission: [],
checkedFilesDownload: [],
lastCheckedIdx: -1,
checkedCount: 0,
paginatedData: [
{"link":"images/2020/08/20200803.jpg","idfile":296,"idaccess":2},
{"link":"images/2020/08/20200807.jpg","idfile":6,"idaccess":99},
{"link":"images/2020/08/20200812.jpg","idfile":26,"idaccess":29},
{"link":"images/2020/08/202123.jpg","idfile":960,"idaccess":2919},
{"link":"images/2020/08/2020032.jpg","idfile":16,"idaccess":9339},
{"link":"images/2020/08/20200000.jpg","idfile":2,"idaccess":9},
]
};
I think main problem that VUE somehow block input with v-model
I have come up with a solution to your problem. I have added a mock object to recreate the same scenario hoping that you have a array of objects.
Editted : Solution has been modified to cater multiple deselect scenario
new Vue({
el: '#app',
data: {
paginatedData: [
{"link":"https://img.icons8.com/list","idfile":296,"idaccess":2},
{"link":"https://img.icons8.com/list","idfile":6,"idaccess":99},
{"link":"https://img.icons8.com/list","idfile":26,"idaccess":29},
{"link":"https://img.icons8.com/list","idfile":960,"idaccess":2919},
{"link":"https://img.icons8.com/list","idfile":16,"idaccess":9339},
{"link":"https://img.icons8.com/list","idfile":2,"idaccess":9},
],
lastCheckedIdx: -1,
checkedFilesPermission : []
},
methods: {
onClickWithShift(event, idx, idFile) {
var action = (this.checkedFilesPermission.indexOf(idFile) === -1) ? 'select' : 'deselect';
if (event.shiftKey && this.lastCheckedIdx !== -1) {
var start = this.lastCheckedIdx;
var end = idx-1;
// can select top to bottom or bottom to top
// always start with lesser value
if (start > end) {
start = idx+1;
end = this.lastCheckedIdx;
}
for (var c = start; c <= end; c++) {
var currentIdFile = this.paginatedData[c]['idfile'];
this.markSelectDeselect(c, action, currentIdFile);
}
}
this.markSelectDeselect(idx, action, idFile);
this.lastCheckedIdx = idx;
if (this.checkedFilesPermission.length === 0) {
//reset last checked if nothing selected
this.lastCheckedIdx = -1;
}
},
markSelectDeselect(idx, action, idFile) {
var currentPos = this.checkedFilesPermission.indexOf(idFile);
if (action === 'select' && currentPos === -1) {
this.checkedFilesPermission.push(idFile);
} else if (action === 'deselect' && currentPos !== -1){
this.checkedFilesPermission.splice(currentPos, 1);
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<div
class="data__file"
v-for="(data, index) in paginatedData"
:key="index"
>
<input
:id="data.idfile"
type="checkbox"
class="data__access"
:value="data.idfile"
v-model="checkedFilesPermission"
/>
<label class="data__info" :for="data.idfile" #click="onClickWithShift($event, index, data.idfile)">
<img
:src="data.link"
alt=""
:class= "{ 'data__image' : 1 ,'data__image-active' : (checkedFilesPermission.indexOf(data.idfile) !== -1) }"
/>
</label>
</div>
</div>
You need to click on the image icon to see the result, since you have mentioned the input is hidden. I kept it visible here so that you can see it is actually getting changed
Here's something I just tried that seems to do the work
<template>
<div>
<div v-for="(item, index) in items" :key="index">
<label>
<input type="checkbox" v-model="item.checked" #click="checked($event, index)">
{{item.file}}
</label>
</div>
<pre>{{items}}</pre>
</div>
</template>
<script>
export default {
data() {
return {
lastCheckedIndex: null,
lastChange: null,
items: [
{ file: "foo1", idx: 10 },
{ file: "foo2", idx: 20 },
{ file: "foo3", idx: 40 },
{ file: "foo4", idx: 30 },
{ file: "foo5", idx: 10 },
{ file: "foo6", idx: 90 },
{ file: "foo8", idx: 50 },
]
}
},
methods: {
checked(event, index) {
// wheter or not to the multiple selection
if (event.shiftKey && (null != this.lastCheckedIndex) && (this.lastCheckedIndex != index)) {
const dir = index > this.lastCheckedIndex ? 1 : -1; // going up or down ?
const check = this.lastChange; // are we checking all or unchecking all ?
for (let i = this.lastCheckedIndex; i != index; i += dir) {
this.items[i].checked = check;
}
}
// save action
this.lastCheckedIndex = index;
this.lastChange = !this.items[index].checked; // onclick is triggered before the default change hence the !
}
},
};
</script>
Related
I have this data coming from another component
on the basis of active tag when row is clicked I am pushing Id to ngModel of checkbox input field.
Row click is working fine and checkbox is adding/removing data
but now when I click on checkbox itself it doesn't do anything like checkbox click function is not working
How can I solve that?
html component
<ngb-panel [disabled]="true" *ngFor="let testPanel of otherTests; let i = index;" id="{{testPanel.Id}}" [title]="testPanel.Name">
<ng-template ngbPanelTitle>
<div class="action-items">
<label class="custom-control custom-checkbox">
<input
type="checkbox"
class="custom-control-input"
[name]="testPanel.Id + '-' + testPanel.Moniker"
[ngModel]="panelIds.indexOf(testPanel.Id) > -1"
(ngModelChange)="onPanelCheckboxUpdate($event, testPanel)"
[id]="testPanel.Id + '-' + testPanel.Moniker">
<span class="custom-control-indicator"></span>
</label>
</div>
</ng-template>
</ngb-panel>
ts component
getting Id from service and push it on basis of row click
this.testOrderService.refreshRequestsObservable().subscribe(
data => {
this.panelActive = data.active;
let testFilteredArray = lodash.filter(this.otherTests, item => item.Id === data.id);
if (this.panelActive) {
// is checked
this.panelIds.push(data.id);
if(testFilteredArray.length > 0){
this.selectedPanels.push(testFilteredArray[0]);
}
}
else {
//is false
this.panelIds = this.panelIds.filter(obj => obj !== data.id);
this.selectedPanels = this.selectedPanels.filter(obj => obj.Id !== data.id);
}
// this.panelIds = lodash.uniq(this.panelIds);
this.selectedPanels = lodash.uniqBy(this.selectedPanels, "Id");
this.updateSession();
}
)
checkbox function
onPanelCheckboxUpdate($event: boolean, panel: TestOrderPanel) {
let testPanelIds = panel.Tests.map(test => test.Id);
// Wipe any duplicates
this.panelIds = this.panelIds.filter(
panelId => panel.Id !== panelId && testPanelIds.indexOf(panelId) === -1
);
this.selectedPanels = this.selectedPanels.filter(
selectedPanel =>
panel.Id !== selectedPanel.Id &&
testPanelIds.indexOf(selectedPanel.Id) === -1
);
if ($event) {
this.panelIds.push(panel.Id);
this.selectedPanels.push(panel);
}
this.updateSession();
}
This checkbox function is not working and wont let me change the value of checkbox.
And also is there any way of adding click function in ngbPanel tag?
Any help?
Thanks
If you want to achieve two way data binding , use below code.
In foo.html
<input [(ngModel)]="checBxFlag" type="checkbox"/>
In App.module.ts
import { FormsModule } from '#angular/forms';
#NgModule({
imports: [
[...]
FormsModule
],
[...]
})
If you want fire event click of check box ,use (onClick)="somemethod()" in your foo.html file and define method in foo.ts file.
I have made a codepen demonstrating a problem I'm having with a checkbox not working. On changes, the value of clipsData does not get updated.
https://codepen.io/bozlurrahman/pen/BeZVzR?editors=1010
<div id="video-clips-wrap">
<div>{{clipsData}}</div>
<li v-for="(clip, index) in clips" v-bind:key="index">
<div class="vl-subsource-container">
<input type="checkbox" value="issubsource" v-model="clip.subsourcesettings" v-on:change="viewSubSource(index)"><label>Not Update on change: {{clip.issubsource}}</label>
<div v-if="clip.subsourcesettings.length">
<label>Dynamic Contents</label>
</div>
</div>
<div class="meditations-options">
<label>Meditations: </label>
<input type="checkbox" value="motivation" v-model="clip.meditations"><label>1. Motivation</label>
<input type="checkbox" value="gratitude" v-model="clip.meditations"><label>2. Gratitude</label>
</div>
</li>
</div>
var video_clip_data_var = "[{\"meditations\":[\"motivation\",\"gratitude\"]}]";
var VideoClip = new Vue({
el: '#video-clips-wrap',
data: {
clips: [],
loading: false,
},
created: function () {
this.clips = JSON.parse(video_clip_data_var);
for (var i = 0; i < this.clips.length; i++) {
// if( typeof this.clips[i].meditations == "string" )
// this.clips[i].meditations = this.clips[i].meditations.split(',');
this.clips[i].subsourcesettings = "issubsource".split(',');
this.clips[i].subsources = [];
}
},
methods: {
viewSubSource: function (index) {
console.log(`this.clips[`+index+`].subsourcesettings`,this.clips[index].subsourcesettings);
console.log(`this.clips`,this.clips);
// this.clipsData = JSON.stringify(this.clips);
},
},
computed: {
clipsData: function () {
return JSON.stringify(this.clips);
},
}
});
Is there any one who can help me to fix this problem? When clicking on the check box, the hidden content should show directly.
Thanks.
Replace that
this.clips[i].subsourcesettings = "issubsource".split(',');
this.clips[i].subsources = [];
to
Vue.set(this.clips[i], 'subsourcesettings', "issubsource".split(','))
Vue.set(this.clips[i], 'subsources', [])
Here you can find more details about your problem.
I am using angular reactive form and making distance input fields which has two input boxes called From and To.
HTML:
<form [formGroup]="form">
<button (click)="addRow()">Add</button>
<div formArrayName="distance">
<div
*ngFor="let item of form.get('distance').controls; let i = index"
[formGroupName]="i"
style="display: flex"
>
<input type="number" placeholder="From" formControlName="from" />
<div><input type="number" placeholder="To" formControlName="to" /></div>
</div>
</div>
<br /><br />
<button type="submit" [disabled]="!form.valid">Submit</button>
</form>
TypeScript:
ngOnInit() {
this.form = this.fb.group({
distance: this.fb.array([]),
});
this.addRow()
}
addRow() {
const control = this.form.controls.distance as FormArray;
control.push(this.fb.group({
from: ['',Validators.required],
to: ['',Validators.required]
}));
}
Here you could able to see the two input boxes in default as from and to.
There is an add button at top and upon clicking add button the rows with same input fields gets added and forms as array.
Here i am in the need of restriction that user should not allowed to enter the previous row to value and also not the value lesser than that.
For eg.,
In the first row, if user enters the below values like 0 and 5 for from and to respectively,
"distance": [
{
"from": 0,
"to": 5
}
]
After clicking add and in second row in From input box user needs to be restricted on adding the values of 5 and lesser than that (which means those values were already entered).
So like this is invalid,
{
"distance": [
{
"from": 0,
"to": 5
},
{
"from": 5,
"to": 10
}
]
}
Here "from": 5, or "from": 4(or)3(or)2(or)1, anything is invalid in second row..
Only 6 and greater than 6 is valid.
Likewise for each row it needs to check for previous row to value and validation needs to be done.
Kindly help me to achieve this type of validation of restricting the user not to enter previous row to value (or) lesser than that in current row's from value.
Working Example: https://stackblitz.com/edit/disable-group-control-value-on-another-control-value-for-j58atx
Edit:
Tried with input change like,
<input type="number" (input)="onInputChange($event.target.value)" placeholder="From" formControlName="from">
in the link https://stackblitz.com/edit/disable-group-control-value-on-another-control-value-for-ymfpkj but not sure whether i am going correct..
Kindly change if this procedure is wrong.
Finally I decided divide the two conditions. see new stackblitz
ngOnInit() {
this.form = this.fb.group({
distance: this.fb.array([], this.distanceValidator()),
});
this.addRow()
}
addRow() {
const control = this.form.controls.distance as FormArray;
control.push(this.fb.group({
from: ['', Validators.required],
to: ['', Validators.required]
}, { validator: this.greaterValidator() }));
}
setDefault() {
const control = this.form.controls.distance as FormArray;
this.default.forEach(data => {
control.push(this.fb.group({
from: [data.from, Validators.required],
to: [data.to, Validators.required]
}, { validator: this.greaterValidator() }));
});
}
greaterValidator() {
return (fa: FormGroup) => {
return fa.value.to && fa.value.to < fa.value.from ? { error: "from greater than to" } : null;
}
}
distanceValidator() {
return (fa: FormArray) => {
let ok = true;
for (let i = 1; i < fa.value.length; i++) {
ok = (!fa.value[i].from || fa.value[i].from > fa.value[i - 1].to) && (!fa.value[i].to || fa.value[i].to > fa.value[i - 1].from);
if (!ok)
return { error: "from/to yet included", index: i }
}
return null
}
}
And the .html
<form [formGroup]="form">
<button (click)="addRow()">Add</button>
<div formArrayName="distance" >
<div
*ngFor="let item of form.get('distance').controls; let i = index"
[formGroupName]="i"
style="display: flex">
<input type="number"
placeholder="From"
formControlName="from">
<div>
<input type="number"
placeholder="To"
formControlName="to">
</div>
<span *ngIf="item.errors">*</span>
<span *ngIf="form.get('distance')?.errors && form.get('distance')?.errors.index==i">**</span>
</div>
</div>
<div *ngIf="form.get('distance')?.errors">{{form.get('distance')?.errors.error}}</div>
<br><br>
<button type="submit" [disabled]="!form.valid"> Submit </button>
</form>
<button (click)="setDefault()"> Set Default Values </button>
Update:Actually only when find an error not control more.
Moreover, if the from and to before is empty, don't give an error. For avoid this we can "convert" to number, writing
let ok = (!fa.value[i].from || fa.value[i].from > +fa.value[i - 1].to)
&& (!fa.value[i].to || fa.value[i].to > +fa.value[i - 1].from);
(see the "+" in +fa.value[i-1].to and +fa.value[i-1].from
Well, As we decided the error we send, imagine you has 6 rows and the line in position 0, in position 3 and in position 4 (0 is the first row) send a error like
{error:"there are errors",indexError:",0,3,4,"}
This allow inside the *ngFor write some like
<span *ngIf="form.get('distance')?.errors &&
form.get('distance')?.errors.indexError.indexOf(','+i+',')>=0">
**
</span>
Well, our distanceValidator becomes like
distanceValidator() {
return (fa: FormArray) => {
let indexError:string="";
for (let i = 1; i < fa.value.length; i++) {
let ok = (!fa.value[i].from || fa.value[i].from > +fa.value[i - 1].to) && (!fa.value[i].to || fa.value[i].to > +fa.value[i - 1].from);
if (!ok)
indexError+=','+i;
}
return indexError?{error:"there are errors",indexError:indexError+','}:null
}
Someone can think that it's better return an array of errors, but this not allowed as to know in a easy way the row with errors. some like errors.find(x=>x.id==i) not work because we can not use find in a interpolation.
It's true that only compare one row with the inmediaty before. It's possible to check over all before -using a for (let j=i-1;j>0;j++){ok=ok && ...}-, but I think it's not necesary and we must be stingy in code. Remember that the function distanceValidator are executed several times
See another stackblitz
Just use a customValidation (I choose the validation in the same component
ngOnInit() {
this.form = this.fb.group({
distance: this.fb.array([], this.distanceValidator()),
});
this.addRow()
}
distanceValidator() {
return (fa: FormArray) => {
let ok = true;
let ok2 = fa.value.length ? (!fa.value[0].to || !fa.value[0].from) || fa.value[0].to > fa.value[0].from : true;
if (!ok2)
return { error: "from greater than to" }
for (let i = 1; i < fa.value.length; i++) {
if (fa.value[i].from && fa.value[i].to )
{
ok = (fa.value[i].from > fa.value[i - 1].to || fa.value[i].to < fa.value[i - 1].from);
ok2 = (fa.value[i].to > fa.value[i].from);
if (!ok)
return { error: "from/to yet included" }
if (!ok2)
return { error: "from greater than to" }
}
}
return ok && ok2 ? null : !ok?{ error: "from yet included" }:{ error: "from greater than to" }
}
}
You can see the error like another
<div *ngIf="form.get('distance')?.errors">
{{form.get('distance')?.errors.error}}
</div>
see [stackblitz forked][1]
Sorry for this lengthy question. I am new to knockout.js.
My business case:
I have a panel with two checkboxes(Yes/No) inside a foreach loop. For some group of items, when one item is selected with 'Yes' checkbox , I need to uncheck 'Yes' checkbox for other items in the group and select the 'No' checkbox for those items.
I am using checked event which is bound to observable array (Yes/No in separate observable arrays).
Items are grouped together by an attribute.(My business case)
One Observable array will hold the 'Yes' selected items.
Another observable array will hold 'No' selected items.
I have a subscribed method to the 'Yes' observable array.
Inside that I have the logic to remove items in the group who already has 'Yes' selected from this observable array.
The subscribe function is called when user 'checks' the checkbox and is also called when the observable array is changed inside the subscribe method due to my logic which I have explained above in Point 6.
Problem: Things seem to work fine which I am able to see through debugging through developer tools, but when the logic to remove the already selected value is executed it is not reflected in the UI. Checkboxes still shows 'Yes' as selected for more than 1 item in the group.
Ex: When One of the item's 'Yes'checkbox is selected in the group the other items 'Yes'checkbox in the group must be unselected. This seems to reflect in the variable values but the UI shows the other items still have 'Yes' checkbox as selected.
My Observable array which holds the 'Yes' selected items still shows the correct values in it(in console) but the UI shows more than 1 item has 'Yes' selected.
Please let me know the issue here.
Html:
<div data-bind="template: { name: 'ItemTemplate', foreach: Items }"></div>
<script type="text/html" id="ItemTemplate">
<!-- Other Html stuffs -->
<div id="SelectionPanel" class="SelectionPanel checkStyle">
<label>
<input type="checkbox" data-bind="value: Id(), click: $root.PersistAutoSelection, checked: $root.SelectedItem, attr: { 'class': SelectStyle, id: 'itemPanelSelected' + $index(), name: 'SelectedIds'}" />
<label data-bind="attr: { 'for': 'PanelSelected' + $index() }">
<p>Yes</p>
</label>
</label>
</div>
<div id="NotRequiredPanel">
<div class="checkbox checkStyle">
<input type="checkbox" class="not-required" data-bind="value: Id(), click: $root.Deselect.bind($data, Id().toString()),checked: $root.NotRequired,attr: { id: 'PanelNotRequired' + $index(), name: 'NotRequiredIds' }" />
<label data-bind="attr: { 'for': 'PanelNotRequired' + $index() }">
<p>No</p>
</label>
</div>
</div>
</script>
Knockout.js script:
var currentlySelectedObject = null;
var isExcessModified = false;
function ViewModel() {
var self = this;
self.SelectedItem = ko.observableArray([]);
self.NotRequired = ko.observableArray([]);
self.Select = function (index) {
self.SelectedItem.push(index.toString());
}
self.Deselect = function (index) {
self.SelectedItem.remove(index.toString());
self.NotRequired.remove(index.toString());
self.NotRequired.push(index.toString());
return true;
}
self.SelectedItem.subscribe(function (newValue) {
var unselectedItem = ko.utils.arrayMap(self.Items(), function (item) {
return item.Id().toString();
});
ko.utils.arrayForEach(self.SelectedItem(), function (itemId) {
ko.utils.arrayRemoveItem(unselectedItem , itemId.toString());
});
if (isExcessModified)
self.ExcessProtectSelectValidation(currentlySelectedObject);
});
self.Remove = function (name) {
ko.utils.arrayForEach(self.Items(), function (item) {
if (item.Name().toLowerCase() == name.toLowerCase()) {
var itemId = item.Id().toString();
self.SelectedItem.remove(itemId);
self.NotRequired.remove(itemId);
}
});
}
self.PersistAutoSelection = function (data, event) {
self.NotRequired.remove(data.Id().toString());
if (!$('#itemPanelSelected' + data.Id().toString()).is(':checked'))
self.SelectedItem.remove(data.Id().toString());
currentlySelectedObject = event.target;
isExcessModified = true;
return true;
}
self.ExcessProtectSelectValidation = function (obj) {
isExcessModified = false;
var yesNoPanel = $(obj).closest('div.bottom');
var schId = $(obj).closest('div.bottom').prev().prev().find("[id^=SchemeID]").val();
if (schId == "AC1" || schId == "AC2" || schId == "AC3") {
//Condition to choose any one of the item
if ($(obj).is(':checked')) {
if (isExcessSelected) {
var itemId = $(obj).closest('[id^="itemPanelInner"]').attr("panelId");
//Logic to remove error message for previous selection
$('*[id*=SchID]').each(function (index) {
if ($(this).val() != schCodeId && ($(this).val() == "AC1" || $(this).val() == "AC2" || $(this).val() == "AC3")) {
Code to show tooltip here;
}
});
//Show error message if try to choose the more than one item had chosen
AddErrorToolTip(yesNoPanel, ToolTipContent);
self.NotRequired.push(itemId.toString());
self.SelectedItem.remove(itemId.toString());
}
else {
//Logic to deselect the other two item, if one the item is already selected
yesNoPanel.removeClass("ErrorHighlight");
yesNoPanel.qtip("destroy", true);
isExcessSelected = true;
if (schId == "AC1" || schId == "AC2" || schId == "AC3") {
$('*[id*=SchID]').each(function (index) {
if ($(this).val() == "AC1" || $(this).val() == "AC2" || $(this).val() == "AC3") {
var itemId = $(this).closest('[id^="itemPanelInner"]').attr("panelId");
if ($(this).val() != schId && ($(this).val() == "AC1" || $(this).val() == "AC2" || $(this).val() == "AC3")) {
var yesNoPanel = $(this).closest('div.top').next().next();
yesNoPanel.removeClass("ErrorHighlight");
yesNoPanel.qtip("destroy", true);
self.NotRequired.push(itemId.toString());
$('#itemPanelSelected' + itemId.toString()).attr('checked', false);
self.SelectedItem.remove(itemId.toString());
}
}
})
}
}
}
else {
isExcessSelected = false;
$('*[id*=SchID]').each(function (index) {
if ($(this).val() == "AC1" || $(this).val() == "AC2" || $(this).val() == "AC3") {
if ($(this).closest("div.top").next().next().find('[id^="ItemPanelNotRequired"]').is(':checked')) {
//Logic to remove the error message if already selected item is unselected
if ($(this).closest('[id^="ItemPanelInner"]').find('div.bottom.ErrorHighlight').length > 0) {
var errorAttachedPanel = $(this).closest('[id^="ItemPanelInner"]').find('div.bottom');
errorAttachedPanel.removeClass("ErrorHighlight");
errorAttachedPanel.qtip("destroy", true);
}
}
}
})
}
}
}
}
In this piece of code I want to add validation to input field, if the value is 0 but I don't know why I am not able to update and enter new value in the input field. Simply I am not able to change the input field value.
Value remain same if I delete existing value and add something in existing value.
Here is HTML code:
<input ng-model="lineitemDetailsCtrlAs.lineItems.orderedQuantity" type="text" class="col-md-6 text-right panel-row-spacing"
ng-keydown="valueChanged($event)" required
/>
and angular code is:
$scope.valueChanged = function (event) {
var quantityRequire={};
if (event.keyCode === 48 || lineitemDetailsCtrlAs.lineItems.orderedQuantity == 0) {
quantityRequire = {
"messageId": "ORDERED_QUANTITY",
"params": [],
"severity": "ERROR"
};
lineitemDetailsCtrlAs.errorMessages.push(quantityRequire);
}
else{
event.preventDefault();
}
};
you are stopping event by "event.preventDefault();", because only keycode 48 (only number 0) is acceptable others keyevents are falling down on else condition and stop updating input value.
I think Rameshkumar Arumugam is right about what's wrong with your code, below is a working example
angular.module("myApp", [])
.controller("MainCtrl", function($scope) {
$scope.lineItems = {
orderedQuantity: 12
};
$scope.errorMessages = [];
$scope.valueChanged = function(event) {
var quantityRequire = {};
if (event.keyCode === 48 || $scope.lineItems.orderedQuantity == 0) {
quantityRequire = {
"messageId": "ORDERED_QUANTITY",
"params": [],
"severity": "ERROR"
};
alert(quantityRequire["messageId"]);
$scope.errorMessages.push(quantityRequire);
}
};
})
<div ng-app="myApp">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<div ng-controller="MainCtrl">
<input ng-model="lineitemDetailsCtrlAs.lineItems.orderedQuantity" type="text" class="col-md-6 text-right panel-row-spacing" ng-keydown="valueChanged($event)" required />
</div>
</div>