Why does the checkbox keep being unchecked by this javascript? - javascript

I have an issue with the following js. It sounds very silly but the following js keeps unchecking the 2 first checkbox (in <div id="shortcut1"></div> and <div id="shortcut2"></div>).
I tested the script with different option, changing the params in cmdInfo. My conclusion is that no matter what the script will never check the 2 first checkbox at the end.
Do you have any idea regarding the issue. I spend hours on this but I can't figure out.
Thanks a lot for your help !
https://jsfiddle.net/bqaude3h/2/
const URL_PLACEHOLDER = 'your url'
let commands = [
{ name: "shortcut1", description: null, shortcut: "Alt+W" },
{ name: "shortcut2", description: null, shortcut: "Alt+Q" },
{ name: "shortcut3", description: null, shortcut: "Alt+S" }
]
let cmdInfo = {
"shortcut1": {
"storeSearchHistory": true,
"url": "https://test.com",
"history": ['test']
},
"shortcut2": {
"storeSearchHistory": false,
"url": ""
},
"shortcut3": {
"storeSearchHistory": true,
"url": ""
}
}
let html, div, existingHistory;
commands.forEach(cmd => {
html = `
<div id="${cmd.name}" class="sc-div">
<div class="flex-container">
<input type="text" class="shortcut" value="${cmd.shortcut}" />
<input type="url" class="url" placeholder="${URL_PLACEHOLDER}"
value="${cmdInfo[cmd.name].url}" />
</div>
<div class="history-div">
<button>View search history</button>
<input type="checkbox" class="store-search-history" />
<label><small>Save search history</small></label>
</div>
</div>
`
document.querySelector('#shortcuts').innerHTML += html;
try {
existingHistory = Boolean(cmdInfo[cmd.name].history.length)
} catch {
existingHistory = false;
}
div = document.getElementById(cmd.name);
div.querySelector('button').disabled = !existingHistory;
div.querySelector('.store-search-history').checked = cmdInfo[cmd.name].storeSearchHistory;
});

The issue is with this line:
document.querySelector('#shortcuts').innerHTML += html;
You can read about Why is “element.innerHTML+=” bad code?. Basically, the browser will re-parse the constructed DOM multiple times which might cause to break reference.
This is a working example:
let commands = [{
name: "shortcut1",
description: null,
shortcut: "Alt+W"
},
{
name: "shortcut2",
description: null,
shortcut: "Alt+Q"
},
{
name: "shortcut3",
description: null,
shortcut: "Alt+S"
}
]
let cmdInfo = {
"shortcut1": {
"storeSearchHistory": true,
"url": "https://some_url.com"
},
"shortcut2": {
"storeSearchHistory": false,
"url": ""
},
"shortcut3": {
"storeSearchHistory": true,
"url": ""
}
}
let html, div, existingHistory, URL_PLACEHOLDER;
commands.forEach(cmd => {
html = `
<div id="${cmd.name}" class="sc-div">
<div class="flex-container">
<input type="text" class="shortcut" value="${cmd.shortcut}" />
<input type="url" class="url" placeholder="${URL_PLACEHOLDER}"
value="${cmdInfo[cmd.name].url}" />
</div>
<div class="history-div">
<button>
<img src="icons/box-open-solid.svg"> View search history
</button>
<input type="checkbox" class="store-search-history" />
<label><small>Save search history</small></label>
</div>
</div>
`
//document.querySelector('#shortcuts').innerHTML += html;
document.querySelector('#shortcuts').insertAdjacentHTML('beforeend', html);
try {
existingHistory = Boolean(cmdInfo[cmd.name].history.length)
} catch (e) {
existingHistory = false;
}
div = document.getElementById(cmd.name);
div.querySelector('button').disabled = !existingHistory;
div.querySelector('.store-search-history').checked = cmdInfo[cmd.name].storeSearchHistory;
});
<div id='shortcuts'>
</div>

You may use the conditional rendering for the input tag.
let commands = [
{ name: "shortcut1", description: null, shortcut: "Alt+W" },
{ name: "shortcut2", description: null, shortcut: "Alt+Q" },
{ name: "shortcut3", description: null, shortcut: "Alt+S" }
]
let cmdInfo = {
"shortcut1": {
"storeSearchHistory": true,
"url": "https://some_url.com"
},
"shortcut2": {
"storeSearchHistory": false,
"url": ""
},
"shortcut3": {
"storeSearchHistory": true,
"url": ""
}
}
let html, div, existingHistory;
let URL_PLACEHOLDER="your placeholder"
commands.forEach(cmd => {
html = `
<div id="${cmd.name}" class="sc-div">
<div class="flex-container">
<input type="text" class="shortcut" value="${cmd.shortcut}" />
<input type="url" class="url" placeholder="${URL_PLACEHOLDER}"
value="${cmdInfo[cmd.name].url}" />
</div>
<div class="history-div">
<button>
<img src="icons/box-open-solid.svg"> View search history
</button>
${
cmdInfo[cmd.name].storeSearchHistory?
'<input type="checkbox" checked >'
:'<input type="checkbox" >'
}
<label><small>Save search history</small></label>
</div>
</div>
`
document.querySelector('#shortcuts').innerHTML += html;
try {
existingHistory = Boolean(cmdInfo[cmd.name].history.length)
} catch {
existingHistory = false;
}
div = document.getElementById(cmd.name);
div.querySelector('button').disabled = existingHistory;
// div.querySelector('.store-search-history').checked = cmdInfo[cmd.name].storeSearchHistory;
});

Related

Vue.js Loop Input [v-model] updating all form elements not just one

I have form data of:
const form = {
title: null,
content: null,
language: {
en: { title: null, content: null },
es: { title: null, content: null }
}
}
My Form inputs
<v-form ref="formEl" #submit.prevent="validate">
<div v-if="Object.keys(form.language).length > 0">
<div v-for="(language, langCode) in form.language" :key="langCode">
<v-text-field
v-model="form.language[langCode].title"
:label="$t('form.title')"
/>
<v-textarea
v-model="form.language[langCode].content"
:label="$t('form.content')"
/>
</div>
</div>
</form>
Now when I change the input of 1 form input, it updates both to be the same.
I tried placed a KEY on each input field, with the same result. Does anyone have any thoughts or direction on this? Much appreciated.
const form = ref(lodash.cloneDeep(state.pages.one))
// GET CONTENT
useFetch(async () => {
loading.value = true
try {
await dispatch('pages/getOne', route.value.params.id).then((res) => {
if (res !== false) {
form.value = lodash.cloneDeep(res)
}
})
} catch(e) {
$system.log({
comp: 'AdminPagesEdit', msg: 'useFetch', val: e
})
} finally {
loading.value = false
}
})

How can I check if fields are empty on Send Message button?

<template>
<div>
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" v-model="firstName" placeholder="Enter your name">
</div>
<div class="form-group">
<label for="lastName">Last name</label>
<input type="text" class="form-control" v-model="lastName" placeholder="Enter your last name">
</div>
<div class="form-group">
<label for="message">Type Your message</label>
<textarea class="form-control" v-model="message" rows="3"></textarea>
</div>
<div class="form-group form-check" v-for="number in numbers" :key="number">
<input type="checkbox" :value="number.Broj" v-model="checkedNumbers">
<label class="form-check-label" >{{number.Broj}}</label>
</div>
<button type="submit" class="btn btn-primary" v-on:click="alert" #click="sendMessage">Send message</button>
</div>
</template>
<script>
import http from "../http-common.js";
import userServices from "../services/userServices.js";
export default {
data()
{
return {
firstName: null,
lastName: null,
message: null,
numbers: "",
checkedNumbers: [],
success: 'You have submitted form successfully'
};
},
methods:
{
async sendMessage()
{
await http.post("/message", {firstName: this.firstName, lastName: this.lastName, message: this.message, numbers: this.checkedNumbers});
this.$data.firstName = "",
this.$data.lastName = "",
this.$data.checkedNumbers = [],
this.$data.message = "";
},
alert() {
alert(this.success)
if(event)
alert(event.target.tagName)
},
retrieveNumbers() {
userServices.getNumbers().then(response => {
this.numbers = response.data;
console.log(response.data);
})
.catch(e => {
console.log(e);
});
}
},
created() {
this.retrieveNumbers();
}
}
</script>
So I want to add the option of checking input fields when user clicks "Send Message" button. I tried some options but I faield at that. So please I would appretiate if someone would help me. I'm still learning.
I know I have to use v-if and create the method for checking the fields.
So if you would be most kind and help me solve this problem I would be really grateful.
Thank you dev, community <3
Can I please get a concrete answer. Because I'll learn in that way, so please without condescending and "no-answers"
You can do it manually :
<script>
import http from "../http-common.js";
import userServices from "../services/userServices.js";
export default {
data()
{
return {
firstName: null,
lastName: null,
message: null,
numbers: "",
checkedNumbers: [],
success: 'You have submitted form successfully'
};
},
methods:
{
async sendMessage()
{
if(!(this.firstName && this.lastName && this.numbers)) return;
await http.post("/message", {firstName: this.firstName, lastName: this.lastName, message: this.message, numbers: this.checkedNumbers});
this.$data.firstName = "",
this.$data.lastName = "",
this.$data.checkedNumbers = [],
this.$data.message = "";
},
alert() {
alert(this.success)
if(event)
alert(event.target.tagName)
},
retrieveNumbers() {
userServices.getNumbers().then(response => {
this.numbers = response.data;
console.log(response.data);
})
.catch(e => {
console.log(e);
});
}
},
created() {
this.retrieveNumbers();
}
}
</script>
Or you can this usefull library
https://vuelidate.js.org/#sub-basic-form
You can simply define a method to check the fields and call that before the HTTP request in the sendMessage method.
You can initialize your data as an empty string "" and have a method like this:
validateForm() {
return this.firstName != "" && this.lastName != "" && this.message != ""
}
Update your sendMessage method to something like this:
async sendMessage() {
const isFormValid = this.validateForm()
if (isFormValid) {
await http.post(....)
...
}
}

Uncaught TypeError: renderIncomes.overIncome is not a function at HTMLInputElement.<anonymous>

I'm currently learning Javascript at school, so my codes may look like a beginner coding style.
I wanted my list(arrays) on the browser to change when I check the checkbox input. But, when I do check the checkbox, it will say this, "Uncaught TypeError: renderIncomes.overIncome is not a function at HTMLInputElement."
In my html file, I set up the input as a checkbox type. And in my javascript file, I added an eventlistener to change when I check the checkbox. The list on the browser should only change when the income is greater than 300. Here are the codes to both html and javascript files.
let user = {
firstName: 'Zoraida',
lastName: 'Rodriguez',
accountType: 'Personal'
}
let renderUser = {
renderName: function() {
const h1 = document.createElement('h1')
h1.textContent = `Welcome ${user.firstName}!`
document.querySelector('#user').appendChild(h1)
}
}
renderUser.renderName()
let incomes = [{
type: 'monthly wages',
date: '09/01/2018',
income: 900,
}, {
type: 'yardwork',
date: '09/07/2018',
income: 100,
}, {
type: 'eBay',
date: '09/14/2018',
income: 250,
}]
let renderIncomes = {
renderList: function() {
document.querySelector('#incomes').innerHTML = ''
const h3 = document.createElement('h3')
h3.textContent = `You have a list of ${incomes.length} incomes.`
document.querySelector('#incomes').appendChild(h3)
incomes.forEach(function(each) {
const p = document.createElement('p')
p.textContent = `On ${each.date}, you received $${each.income} from ${each.type}.`
document.querySelector('#incomes').appendChild(p)
})
},
totalIncome: function() {
document.querySelector('#totalIncome').innerHTML = ''
let totalIncome = 0
incomes.forEach(function(income) {
totalIncome += income.income
})
const h2 = document.createElement('h2')
h2.textContent = `Total income: $${totalIncome}`
document.querySelector('#totalIncome').appendChild(h2)
},
overIncome: function() {
incomes.filter(function(incomeResults) {
return incomeResults.income > 300
})
}
}
renderIncomes.renderList()
renderIncomes.totalIncome()
renderIncomes.overIncome()
document.querySelector('#new-incomes').addEventListener('submit', function(e) {
e.preventDefault()
incomes.push({
type: e.target.elements.typeOfIncome.value,
date: e.target.elements.date.value,
income: parseInt(e.target.elements.income.value)
})
renderIncomes.renderList()
renderIncomes.totalIncome()
e.target.elements.typeOfIncome.value = ''
e.target.elements.date.value = ''
e.target.elements.income.value = ''
})
document.querySelector('#filterincomes').addEventListener('change', function(e) {
renderIncomes.overIncome = e.target.checked
renderIncomes.overIncome()
})
<body>
<div id="user" class="center"></div>
<hr>
<br>
<div id="totalIncome" class="center"></div>
<div id="incomes" class="center"></div>
<form id="new-incomes" class="center">
<label>
Date: <input type="text" placeholder="MM/DD/YYYY" name="date">
</label>
<label>
Type: <input type="text" placeholder="From Where" name="typeOfIncome">
</label>
<label>
Income: <input type="text" placeholder="Type New Income" name="income">
</label>
<button>Submit</button>
</form>
<label>
<input id="filterincomes" type="checkbox">Check here for incomes over $300
</label>
<script src="test.js"></script>
</body>
you are assigning property overIncome of object renderIncomes to boolean value
so there is no function overIncome() after line
renderIncomes.overIncome = e.target.checked
remove the line, your code will work fine
In your addEventListener you are assigning a value to a object
Change the below code as commend and please note below solution will fix your Uncaught TypeError error
document.querySelector('#filterincomes').addEventListener('change', function(e) {
//renderIncomes.overIncome = e.target.checked
renderIncomes.overIncome()
})

Knockout foreach array checkboxes are not visually updating

I have a json array that has elements created in a foreach databind.
Then I'm retaining the selected object in that array so that I can have independent "Save Changes" buttons for each object in that array. All of that is working (primarycontactname for example) except the binding for the checkboxes.
<div class="container span8" data-bind="foreach: locationssubscribed">
<div class="well span3" data-bind="click: $parent.selectedLocationSubscribed">
<input type="text" class="span3" data-bind="value: primarycontactname" placeholder="Contact Name.." />
<br />
<div class="checkbox" data-bind="visible: (vendorbringinggifts() === 0 || vendorbringinggifts() === vendorid())">
<input id="chkGiftsAreBeingBrought" type="checkbox" data-bind="checked: giftsarebeingbrought" />
</div>
<button data-bind="click: $root.saveVendorToLocation, enable: needsave, text: needsave() ? 'Save Location Changes' : 'No Changes to Save', css: { 'btn-primary': needsave }" class="btn">Save Location Changes</button>
</div>
</div
The checkboxes load correctly based on the giftsarebeingbrought observable in each array object but when clicking the checkbox the visible check doesn't toggle. Using the debugger I can see that the observable giftsarebeingbrought in the original array and in the selectedLocationSubscribed are toggling on the first click but then do not toggle again on subsequent clicks and the visual checkbox never changes after the initial binding.
{
"locationssubscribed": [
{
"vendortolocationid": 10,
"primarycontactname": "Fake Name1",
"vendorbringinggifts": 0,
"giftsarebeingbrought": false,
"needsave": false
},
{
"vendortolocationid": 11,
"primarycontactname": "Fake Name2",
"vendorbringinggifts": 0,
"giftsarebeingbrought": false,
"needsave": false
},
{
"vendortolocationid": 12,
"primarycontactname": "Fake Name3",
"vendorbringinggifts": 0,
"giftsarebeingbrought": false,
"needsave": false
},
{
"vendortolocationid": 13,
"primarycontactname": "Fake Name4",
"vendorbringinggifts": 0,
"giftsarebeingbrought": false,
"needsave": false
}
],
"selectedLocationSubscribed": {
"vendortolocationid": 12,
"primarycontactname": "Fake Name1",
"vendorbringinggifts": 0,
"giftsarebeingbrought": true,
"needsave": true
}
}
function VendorToLocation(vtl) {
this.vendortolocationid = ko.observable(vtl.VendorToLocationID);
this.primarycontactname = ko.observable(vtl.PrimaryContactName);
this.vendorbringinggifts = ko.observable(vtl.VendorBringingGifts);
this.giftsarebeingbrought = ko.observable(vtl.GiftsAreBeingBrought);
this.needsave = ko.observable(false);
}
function VendorViewModel() {
var self = this;
self.locationssubscribed = ko.observableArray();
self.selectedLocationSubscribed = ko.observable();
self.selectedLocationSubscribed.subscribe(function (ftl) {
if (ftl !== null) {
ftl.needsave(true);
}
});
self.getLocationsAvailable = function (vendorID) {
self.locationsavailable.removeAll();
$.ajax($("#GetLocationsAvailableUrl").val(), {
data: '{ "vendorID":' + vendorID + '}',
async: false,
success: function (allData) {
self.locationsavailable($.map(allData, function (item) { return new LocationsAvailable(item) }));
}
});
}
self.getLocationSubscription = function (vendorID) {
self.locationssubscribed.removeAll();
$.ajax($("#GetLocationSubscriptionUrl").val(), {
data: '{ "vendorID":' + vendorID + '}',
success: function (allData) {
self.locationssubscribed($.map(allData, function (item) { return new VendorToLocation(item) }));
}
});
}
self.saveVendorToLocation = function () {
var url = $("#updateVendorToLocationUrl").val();
var vendorid = self.selectedVendor().vendorid();
var selectedLoc = self.selectedLocationSubscribed();
$.ajax(url, {
data: '{ "vtl" : ' + ko.toJSON(selectedLoc) + '}',
success: function (result) {
if (result === false) {
toastr.error("ERROR!: Either you or a competing vendor has chosen this location since you last loaded the webpage. Please refresh the page.");
} else {
toastr.success("Vendor to location details saved");
selectedLoc.vendortolocationid(result.VendorToLocationID);
self.updateVendorView(); // added 170307 1030 to get vendor contact details to update automatically
self.getActionLog(vendorid);
selectedLoc.needsave(false);
}
}
});
};
}
$(document).ready(function () {
var myViewModel = new VendorViewModel();
ko.applyBindings(myViewModel);
myViewModel.updateVendorView();
myViewModel.getLocationSubscription(curVendorID);
}
The goal is to get the checkbox working correctly. The rest of the textbox based bindings I removed to condense the post have worked correctly for years some I'm now stumped as to what I'm doing wrong with the textbox.
Let me reconfirm, so you're trying to enable the associated button as well as check the checkbox if a user click on an element inside <div class="well span3 ...>".
I put all the suggestions in the code directly.
function VendorToLocation(vtl) {
var self = this;
self.vendortolocationid = ko.observable(vtl.vendortolocationid);
self.primarycontactname = ko.observable(vtl.primarycontactname);
self.vendorbringinggifts = ko.observable(vtl.vendorbringinggifts);
self.giftsarebeingbrought = ko.observable(vtl.giftsarebeingbrought);
self.needsave = ko.observable(vtl.needsave);
// I prefer to put all the logic in here instead of being embedded to the HTML
self.isCheckboxVisible = ko.pureComputed(function(){
return self.vendorbringinggifts() === 0 || self.vendorbringinggifts() === self.vendortolocationid();
});
}
function VendorViewModel() {
var self = this;
self.locationssubscribed = ko.observableArray(
[
new VendorToLocation ({
"vendortolocationid": 10,
"primarycontactname": "Fake Name1",
"vendorbringinggifts": 0,
"giftsarebeingbrought": false,
"needsave": false
}),
new VendorToLocation ({
"vendortolocationid": 11,
"primarycontactname": "Fake Name2",
"vendorbringinggifts": 0,
"giftsarebeingbrought": false,
"needsave": false
}),
new VendorToLocation ({
"vendortolocationid": 12,
"primarycontactname": "Fake Name3",
"vendorbringinggifts": 0,
"giftsarebeingbrought": false,
"needsave": false
}),
new VendorToLocation ({
"vendortolocationid": 13,
"primarycontactname": "Fake Name4",
"vendorbringinggifts": 0,
"giftsarebeingbrought": false,
"needsave": false
})
]
);
// To store the selected location
self.selectedLocationSubscribed = ko.observable();
// To modify selected location, enable the button and modify the checkbox whenever user click on an element that uses this as its click event
self.selectLocationSubscribed = function(data, event) {
if(data !== null) {
self.selectedLocationSubscribed(data);
// If you want to change needsave of other properties to false (disable all other buttons) before that you can do it here
ko.utils.arrayForEach(self.locationssubscribed(), function(location) {
if(data.vendortolocationid() !== location.vendortolocationid()){
location.needsave(false);
location.giftsarebeingbrought(false);
}
});
// code ends here
// And then you modify the selected needsave the selected object to true to enable the button
data.needsave(true);
data.giftsarebeingbrought(true);
}
// To perform the default browser click action
return true;
}
}
$(document).ready(function () {
var myViewModel = new VendorViewModel();
ko.applyBindings(myViewModel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<div class="container span8" data-bind="foreach: locationssubscribed">
<div class="well span3" data-bind="click: $parent.selectLocationSubscribed">
<input type="text" class="span3" data-bind="value: primarycontactname" placeholder="Contact Name.." />
<br />
<div class="checkbox" data-bind="visible: (vendorbringinggifts() === 0 || vendorbringinggifts() === vendorid())">
<input id="chkGiftsAreBeingBrought" type="checkbox" data-bind="checked: giftsarebeingbrought" />
</div>
<button data-bind="click: $root.saveVendorToLocation, enable: needsave, text: needsave() ? 'Save Location Changes' : 'No Changes to Save', css: { 'btn-primary': needsave }" class="btn">Save Location Changes</button>
</div>
</div>
The click binding prevents the default action. To enable the default action, return true from the event handler. This means you can't directly pass an observable to the click binding.
click: $parent.handleClick
JS:
self.handleClick = function (item) {
// do something with item
return true; // don't prevent default action
}

Conditional validation in VueJS

I am using VueJS with vue-validator and I have been struggling for hours to do simple conditional validation. The example provided in the documentation does not seem to work, at least not in my case.
What I am trying to accomplish is requiring two input groups (observer_firstName and observer_lastName) if a condition (showObserverEntry) is true and requiring another (role) if it is false.
So, if showObserverEntry is false, role should be required/visible. If showObserverEntry is true, role SHOULD NOT be required or visible, observer_firstName and observer_lastName should be required and visible.
Everything works when the page is loaded and showObserverEntry is set to false, it continues to work when switched to true, but when it goes back to false again validation stops working for role. Peeking at the data output, the validation data changes to validation { } where it initially has data.
Vue instance with other methods removed:
var vm = new Vue({
el: "#scheduleContainer",
validator: {
validates: {
requiredIf: function (val, condition){
return val && condition
}
}
},
data: {
loading: true,
stationId: stationId,
date: initialDate,
dateFormatted: initialDateFormatted,
nextDate: null,
prevDate: null,
entries: [],
requestEntries: [],
roles: [],
roleStaff: [],
showObserverEntry: false,
startPickerDatetime: null,
endPickerDatetime: null,
shiftEntry: {
start: null,
end: null,
role: null,
member: "",
observer: {
firstName: "",
lastName: ""
}
}
},
computed: {
validField: function () {
return this.validation.shiftEntry.observer.firstName.valid &&
this.validation.shiftEntry.observer.lastName.valid
}
},
methods: {
getRoleStaff: function () {
if (this.shiftEntry.role != '' && this.shiftEntry.role != 'observer') {
this.$http.post('/members/schedule/manage/json/roles/staff', {id: this.shiftEntry.role})
.success(function (data) {
this.$set('roleStaff', data.members);
vm.shiftEntry.member = "";
vm.showObserverEntry = false;
vm.shiftEntry.observer.firstName = "";
vm.shiftEntry.observer.lastName = "";
});
} else if (this.shiftEntry.role == 'observer') {
this.showObserverEntry = true;
this.resetFields()
}
else {
this.showObserverEntry = false;
this.roleStaff = [];
}
},
resetFields: function () {
this.roleStaff = [];
this.shiftEntry.role = "";
this.shiftEntry.member = "";
this.shiftEntry.observer.firstName = "";
this.shiftEntry.observer.lastName = "";
},
conditionalField: function (response, type) {
return response === type
}
}
});
Form fields:
<div class="form-group"
v-if="conditionalField(showObserverEntry, false)"
v-class="has-error: validation.shiftEntry.member.invalid">
<label for="member">Member:</label>
<select name="member"
id="member"
v-model="shiftEntry.member"
options="roleStaff"
v-attr="disabled: !roleStaff.length"
class="form-control"
v-validate="requiredIf: conditionalField(showObserverEntry, false)">
<option value="">Select Member</option>
</select>
</div>
<div class="form-group"
v-if="conditionalField(showObserverEntry, true)"
v-class="has-error: validation.shiftEntry.observer.firstName.invalid">
<label for="observer_firstName">First Name:</label>
<input type="text"
id="observer_firstName"
class="form-control"
v-model="shiftEntry.observer.firstName"
v-validate="requiredIf: conditionalField(showObserverEntry, true)">
</div>
<div class="form-group"
v-if="conditionalField(showObserverEntry, true)"
v-class="has-error: validation.shiftEntry.observer.lastName.invalid">
<label for="observer_lastName">Last Name:</label>
<input type="text"
id="observer_lastName"
class="form-control"
v-model="shiftEntry.observer.lastName"
v-validate="requiredIf: conditionalField(showObserverEntry, true)">
</div>
It is because a bug in Vue.js. Reason: If we remove one or more v-model based on certain condition(v-if), then it will make all other validation to deactivate.
Refer the issue :https://github.com/vuejs/vue-validator/issues/69

Categories

Resources