Can't select chechbox with v-model in VueJS - vue.js

I have a checkbox as a feature filter for a real estate agency site.
From the database comes the list of categories with their respective characteristics:
public function get_categories(Request $request)
{
$categories = Category::with('features')->get();
return response()->json([
'validation' => true,
'categories' => $categories
]);
}
In the Vue template, I have an accordion with UIKit.
I have one accordion header per category that I walk through using a v-for
Then inside the body of the accordion I have the checkboxes that correspond to the characteristics that belong to that category
<li
v-for="category in categories"
:key="category.id">
<a
href="#"
class="uk-accordion-title">
{{ category.name }}
</a>
<div class="uk-accordion-content">
<div uk-grid>
<div
class="uk-width-1-1 uk-margin-small"
v-for="feature in category.features"
:key="feature.id">
<label>
<input
:id="'feature_' + feature.id"
class="uk-checkbox"
type="checkbox"
name="features"
:value="feature.id"
v-model="features"
#change="filterUpdate"> <!-- ID hacer que este sea venga de la BD -->
{{ feature.name }}
</label>
</div>
</div>
</div>
</li>
To load the categories of course I have a method that is responsible for making the request when creating the component
layoutLoadCategories() {
axios.get('api/layout/get/categories').then( res => {
this.categories = res.data.categories;
});
},
The problem is that when I try to click on a checkbox, nothing happens. Not selected

When you are using v-model you no need to use :value and moreover since its a checkbox input you v-model variable should hold only boolean value (ie) either true or false
<input
:id="'feature_' + feature.id"
class="uk-checkbox"
type="checkbox"
name="features"
v-model="features" // here I guess features is an object or array...so assign a variable that is of type Boolean
#change="filterUpdate">

I have already worked out, in the form tag I had # click.prevent
I have removed the .prevent and it already works
Before:
<form id="filter_form" action="/property-browser" method="get" #click.prevent="filterUpdate">
After:
<form id="filter_form" action="/property-browser" method="get" #click="filterUpdate">

Related

How to filter some vuex data in response to a select change

I'm new to VueJS and still trying to understand all of the constructs. I have a Vuex store and that has several arrays in the state. In a view that uses the vuex store through a computed property, I need to filter the data from the store when a select changes. I don't understand how to wire the select to the officeProjections data in the store.
<select id="busyness"
name="busyness"
class="form-control mt-1"
v-model="workloadLevels"
##change="onWorkloadFilterChange($event)">
<option v-for="wl in workloadLevels" v-bind:value="wl.id">{{ wl.description }}</option>
</select>
<div v-for="op in officeProjections" class="mt-1">
<div class="card">
<div class="card-body">
<h3 class="card-title">{{ op.consultantName }}</h3>
<p>{{ op.workloadLevel }} <button type="button" v-bind:id="op.ConsultantId" class="btn btn-lg btn-info" data-toggle="popover" data-placement="right" v-bind:data-content="op.comment"></button></p>
<p>{{ op.office }}</p>
</div>
</div>
</div>
The model bound to the select cannot be the same as the element in the store serving the arrays, in this case you have v-model="workloadLevels" and `v-for="wl in workloadLevels".
You're going to need a separate model for the selected value:
v-model="selectedWorkloadLevel"
And create that property selectedWorkloadLevel in your Vuex store.
I would not make an action, just a mutation, and I would make it generic:
SET_VALUE: function(state, payload) {
Object.keys(payload).forEach((key) => {
if (state.hasOwnProperty.call(key)) {
state[key] = payload[key]
}
})
}
Then add a get and set computed value for your selectedWorkloadLevel:
get selectedWorkloadLevel() {
return this.$store.getters['selectedWorkloadLevel']
}
set selectedWorkloadLevel(value) {
this.$store.commit('SET_VALUE', { selectedWorkloadLevel: value })
}
Then remove the #change handler and update your v-model:
v-model="selectedWorkloadLevel"

Add Html element in div vuejs

I have been searching for 4 hours , cant even get my head to understand what to use
basically i want to add a new row (article tag) to a div element , everytime the user press the addbutton
in my method how can i pass this HTMLto the div :
<article class="col-md-11 col-md-offset-1 card" custom_attrib=atrrib_value> <span>
{{NEW VALUE}} - {{NEW VALUE_2}}
</span>
<span >
<button class="btn btn-theme btn-default btn-xs pull-left" #click="deleteItem" ><i class="fa fa-times inline"></i></button>
</span>
</article>
I have to say i need to put some custom attrib on the Article tag each time thats why i want to make a new tag on each request
if we take a look at this https://codepen.io/Pizzi/pen/GMOQXy
when pressing the + (add) a row drops , i want to do the same thing but the important part is the new row with article tag needs new custom_attrib and value everytime
another jsfiddle example : https://jsfiddle.net/50wL7mdz/17736/
instead of those input box will be my article with custom attrib and value
You make an array. When the user clicks "add new" you will append a new item to the array which contains HTML with two input fields. When you append it, Vuejs will re-render the HTML with the changed data.
// Vue.js
new Vue({
el: '#app',
data: {
items:[],
item:['NEW VALUE','NEW VALUE_2'],
},
created(){
this.items.push(this.item);
},
methods:
{
add()
{
this.item = ['</br><input type="text"/>','<input type="text"/></br>'];
this.items.push(this.item);
}
}
})
<h2>Vue.js</h2>
<div id="app">
<article class="col-md-11 col-md-offset-1 card" custom_attrib=atrrib_value>
<span v-for="item in items" ><span v-html="item[0]"></span> - <span v-html="item[1]"></span></span>
<span >
<button v-on:click="add" class="btn btn-theme btn-default btn-xs pull-left">
+
</button>
</span>
</article>
</div>
<!-- Vue.js -->
<script src="https://vuejs.org/js/vue.min.js"></script>

Using vue, determine which radio input is selected by accessing $refs

I populate some radio buttons from an array of options. I would like to determine which radio button was select using $refs, however when I log out the $refs it gives me all of the radio buttons.
Is it possible to just grab the select radio button using $refs? Can you some how combine event.target with the $refs or something? Furthermore how to I access parts of that ref like the class of the element that was selected. I am trying to use just vue to do this but has proven difficult.
thanks for any help you can provide.
<li
class="mc-option"
v-for="(option, i) in options"
:key="i">
<input
ref="mcOption"
type="radio"
name="option"
:id="'option-' + i"
class=""
#click="radioSelected($event)">
</li>
methods: {
radioSelected: function () {
let mcOption = this.$refs.mcOption
console.log(mcOption)
},)
}
X is your ID:
<ul>
<li v-for="x in 5">
<label :for="`radio${x}`">radio{{x}}</label>
<input type="radio" name="radio" :id="`radio${x}`" #change="getRef(`radio${x}`)" :ref="`radio${x}`">
</li>
</ul>
methods: {
getRef (ref) {
console.log(this.$refs[ref])
}}
This is happening since all the generated options are having the same ref ids. You could come over this with the following code.
TEMPLATE
<li class="mc-option" v-for="(option, i) in options" :key="i">
<input :ref="['mcOption',i].join('-')" type="radio" name="option" :id="'option-' + i" class="" #click="radioSelected(i)"> {{i+1}}
</li>
JS
methods: {
radioSelected: function (i) {
let mcOption = this.$refs[['mcOption', i].join('-')]
console.log(mcOption)
}
}
Points to note are:
:ref
a variable ref id by using ['mcOption', i].join('-'). This actually can be anything you want (but should change for every v-for iteration).
Please let me know if it does NOT work for you.

v-for loop. i will get same value at each checkbox

i'm going to show a loop for user's favourite music genres. but i want to read them from a property inside my Vue instance. here is my code:
<div id="app">
<form method="post" action="">
<fieldset>
<legend>Genres</legend>
<!-- Item in Collection -->
<div v-for="genre in genres">
<input type="checkbox" v-model="selectedGenres" value="genre"> {{genre}}
</div>
</fieldset>
<input type="submit" value="submit">
</form>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
genres: ['jazz', 'pop', 'blues', 'classic', 'country'],
selectedInterests: []
}
});
</script>
but at the end i will get following image and value attribute of checkboxes will not change! why i will get same values at each checkbox?
i am not sure but i think you should change your code in where it says:
value="genre"
and change it to:
v-bind:value="genre" or :value="genre"
You need to bind the genre variable.
<input type="checkbox" v-model="selectedGenres" :value="genre">
Will compute genre instead of just giving the string genre

How to add Validation for multiple checkboxes in Aurelia?

So I've just got a form set up with a list checkboxes of states so that you can select multiple states, however I'm not quite sure how to put the validation on the collection of checkboxes rather than each individual one.
Right now, I have:
my-view.html
<div repeat.for="territory of availableTerritories" class="form-row">
<input type="checkbox" value.bind="territory" checked.bind="region.territories & validate">
<label>${territory}</label>
</div>
<ul if.bind="validationController.errors">
<li repeat.for="error of validationController.errors">
${error.message}
</li>
</ul>
<button class="button cancel" click.trigger="cancel()">Cancel</button>
<button class="button ok" click.trigger="saveRegion()">Save Territories</button>
my-viewmodel.js
availableTerritories = [
'US-AL',
'US-AK',
...
]
region = {
territories: []
}
constructor(validationController) {
ValidationRules
.ensure(region=>region.territories)
.required()
.minItems(1)
.on(this.region);
}
However, when I test this out with an empty input, I get a ValidationError for every checkbox rather than just the collection of them.
My ValidationError message
Territories must contain at least 1 item.
Territories must contain at least 1 item.
Territories must contain at least 1 item.
...
So I ended up adding a hidden input to the form and doing the validation on that, instead of the checkboxes themselves:
my-view.html
<div repeat.for="territory of availableTerritories" class="form-row">
<input type="checkbox" value.bind="territory" checked.bind="region.territories"> // No validation here
<label>${territory}</label>
</div>
<input type="hidden" value.bind="region.territories & validate"> //Added validation here instead
<ul if.bind="validationController.errors">
<li repeat.for="error of validationController.errors">
${error.message}
</li>
</ul>
<button class="button cancel" click.trigger="cancel()">Cancel</button>
<button class="button ok" click.trigger="saveRegion()">Save Territories</button>