How can I initially mark first radio-button as 'checked'?
items =
[
{txt: 'foo', val: 1},
{txt: 'bar', val: 2}
]
<div v-for="item in items">
<input name="myfield" type="radio" v-bind:value="item.val" v-bind:checked="item.val==comparisonvalue">
<label>{{ item.txt }}</label>
</div>
You probably want to use v-model to bind the input to your data, in which case set an item (e.g. myInput) in your data and then initialize it with the first value in your items array:
new Vue({
el: '#app',
data: {
myInput: 1,
items:
[
{txt: 'foo', val: 1},
{txt: 'bar', val: 2}
]
}
})
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<div id='app'>
<div v-for="item in items">
<input
name="myfield"
type="radio"
v-bind:value="item.val"
v-model="myInput">
<label>{{ item.txt }}</label>
</div>
</div>
Under most circumstances, you might get the items from an API call, and then you can initialize it in created:
new Vue({
el: '#app',
data: {
myInput: null,
items: null
},
created () {
this.items = [
{txt: 'foo', val: 1},
{txt: 'bar', val: 2}
] // or from an API call
this.myInput = this.items[0].val
}
})
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<div id='app'>
<div v-for="item in items">
<input
name="myfield"
type="radio"
v-bind:value="item.val"
v-model="myInput">
<label>{{ item.txt }}</label>
</div>
</div>
Or get the index in v-for and then check whether index === 0 at the input:
new Vue({
el: '#app',
data: {
items:
[
{txt: 'foo', val: 1},
{txt: 'bar', val: 2}
]
}
})
<script src="https://cdn.jsdelivr.net/npm/vue#2.5.16/dist/vue.js"></script>
<div id='app'>
<div v-for="(item, index) in items">
<input
name="myfield"
type="radio"
v-bind:value="item.val"
v-bind:checked="index === 0">
<label>{{ item.txt }}</label>
</div>
</div>
Related
I wanna know how to v-for on a multidimensional array with selected index, because when I go with this code it does not work.
<div v-for="button in pull.button_response[key]">
<p>test</p>
</div>
Thank you
Try this:
//===== just to remove warnings
Vue.config.productionTip = false;
Vue.config.devtools = false
//==============================
new Vue({
el: "#app",
data: {
pull: {
button_response: {
a: [
1, 2, 3, 4, 5
],
b: [
6, 7, 8, 9, 10
]
}
},
key: ['a', 'b']
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<template>
<div>
<select v-model="key">
<option value="a">a</option>
<option value="b">b</option>
</select>
<br/>
<div v-for="button in pull.button_response[key]">
<p>{{button}}</p>
</div>
</div>
</template>
</div>
You can use both, index and object like an enum, so
<div v-for="(index, button) in pull" :key="index">
<p>test {{ button[index] }}</p>
</div>
<template>
<b-form #submit.prevent="Submit" class="mb-5">
<div class="inputArea" v-for="input in inputs" :key="input.id">
<b-form-group label-cols-sm="2" label="Solution (EN)">
<ckeditor :editor="ckeditor" v-model="form.body.en" :config="ckeditorConfig"></ckeditor>
<div v-if="errors['body.en']">
<div v-for="err in errors['body.en']" :key="err">
<small class="text-danger">{{ err }}</small>
</div>
</div>
</b-form-group>
<b-form-group label-cols-sm="2" label="Body (FR)">
<ckeditor :editor="ckeditor" v-model="form.body.np" :config="ckeditorConfig"></ckeditor>
<div v-if="errors['body.np']">
<div v-for="err in errors['body.np']" :key="err">
<small class="text-danger">{{ err }}</small>
</div>
</div>
</b-form-group>
<b-form-group label-cols-sm="2" label="Body (IT)">
<ckeditor :editor="ckeditor" v-model="form.body.in" :config="ckeditorConfig"></ckeditor>
<div v-if="errors['body.in']">
<div v-for="err in errors['body.in']" :key="err">
<small class="text-danger">{{ err }}</small>
</div>
</div>
</b-form-group>
</div>
<b-form-group label="" label-cols-sm="2">
<b-button type="button" class="text-white" variant="dark" #click="addRow">Add row</b-button>
</b-form-group>
<b-form-group label="" label-cols-sm="2">
<b-button type="submit" class="text-white" variant="dark">Submit</b-button>
</b-form-group>
</b-form>
</template>
<style lang="scss">
</style>
<script>
import CKEditor from '#ckeditor/ckeditor5-vue2'
import ClassicEditor from '#ckeditor/ckeditor5-build-classic'
export default {
name: 'Interaction',
components: {
ckeditor: CKEditor.component
},
data(){
return{
counter: 0,
inputs: [
{
en: '',
np: '',
in: '',
}],
form: {
body: [
{
en: '',
np: '',
in: '',
}
],
},
errors: {},
ckeditorData: '<p></p>',
ckeditorConfig: {
// The configuration of the editor
},
ckeditor: ClassicEditor
}
},
methods: {
Submit(){
this.storing = true
this.errors = {}
var self = this
axios.post('/this-is-a-post-url', this.form)
.then(function(response){
console.log(response)
})
},
addRow() {
this.inputs.push({
en: '',
it: '',
fr: '',
id: `${++this.counter}`,
value: '',
});
}
}
}
</script>
I will have array coming in the body name so I am trying to to clone the clone body on a click of a button which has a function AddRow. I want to clone the three fields en,np,in and I want it work like normal html works in this. Example when we clone html form it create input field like so <input name="body['en'][0]"> and when we clone another time it creates something like this <input name="body['en'][1]">.
I have the above code, it clones the body but it also clones the added text before cloning. I want to add an empty field while cloning and also want to update v-model. How can I do that?
Refer below example:
https://codepen.io/telen/pen/OeNZVV
<main class="container">
<form id="app" data-apartments='[{ "price": "23000", "rooms": "12" }, { "price": "42000", "rooms": "32" }]'>
<h1>
Dynamic apartment forms
</h1>
<hr>
<div class="row">
<div class="col-xs-2">
<button type="button" v-on:click="addNewApartment" class="btn btn-block btn-success">
Add +
</button>
</div>
<div class="col-xs-10">
Would you like add more apartments?
</div>
</div>
<div v-for="(apartment, index) in apartments">
<div class="row">
<div class="col-xs-2">
<label> </label>
<button type="button" v-on:click="removeApartment(index)" class="btn btn-block btn-danger">
Rem -
</button>
</div>
<div class="form-group col-xs-5">
<label>Price (HUF)</label>
<input v-model="apartment.price" type="number"
name="apartments[][price]" class="form-control" placeholder="Price">
</div>
<div class="form-group col-xs-5">
<label>Rooms (PCS)</label>
<input v-model="apartment.rooms" type="number"
name="apartments[][rooms]" class="form-control" placeholder="Rooms">
</div>
</div>
</div>
<div class="row">
<div class="col-xs-2">
<button type="submit" v-on:click.prevent="sumbitForm" class="btn btn-block btn-primary">
Submit
</button>
</div>
<div class="col-xs-10">
Open the console (F12) and see the result
</div>
</div>
<hr>
<pre>{{ $data }}</pre>
</form>
JS:
window.app = new Vue({
el: '#app',
data: {
apartment: {
price: '',
rooms: ''
},
apartments: [],
},
mounted: function () {
/*
* The "data-apartments" could come from serverside (already saved apartments)
*/
this.apartments = JSON.parse(this.$el.dataset.apartments)
},
methods: {
addNewApartment: function () {
this.apartments.push(Vue.util.extend({}, this.apartment))
},
removeApartment: function (index) {
Vue.delete(this.apartments, index);
},
sumbitForm: function () {
/*
* You can remove or replace the "submitForm" method.
* Remove: if you handle form sumission on server side.
* Replace: for example you need an AJAX submission.
*/
console.info('<< Form Submitted >>')
console.info('Vue.js apartments object:', this.apartments)
window.testSumbit()
}
}
})
/*
* This is not Vue.js code, just a bit of jQuery to test what data would be submitted.
*/
window.testSumbit = function () {
if (!window.jQuery) {
console.warn('jQuery not present!')
return false
}
console.info('Submitted (serverside) array:', jQuery('form').serializeJSON())
}
new Vue({
el: '#app1',
data: {
objects:[
{
object: {
title: 'C',
author: 'Denis',
publishedAt: '1960'
}
},
{
object: {
title: 'Vue',
author: 'Yet To Find',
publishedAt: '2010'
}
}]}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.0/vue.js"></script>
<div id="app1">
<ol>
<div v-for="object in objects">
{{index}}
<li v-for="value in object">
{{value}}
</li>
</div>
</ol>
</div>
new Vue({
el: '#app1',
data: {
objects:[
{
title: 'C',
author: 'Denis',
publishedAt: '1960'
},
{
title: 'Vue',
author: 'Yet To Find',
publishedAt: '2010'
}]}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.0/vue.js"></script>
<div id="app1">
<ol>
<div v-for="object in objects">
{{index}}
<li v-for="value in object">
{{value}}
</li>
</div>
</ol>
</div>
I am able to achieve these two variations. But I am trying to achieve the below
1.
.C
.Denis
.1960
2.
.
.
.
How can I do it from what I have? I am trying to express bullet/number by Dot(.).
new Vue({
el: '#app',
data: {
objects: [{
title: 'C',
author: 'Denis',
publishedAt: '1960'
},
{
title: 'Vue',
author: 'Yet To Find',
publishedAt: '2010'
}
]
}
})
/*ignore - hide snippets console */
.as-console-wrapper {
max-height: 0px !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.0/vue.js"></script>
<div id="app">
<ul>
<div v-for="(object, index) in objects">
{{ index + 1 }}
<li v-for="(value, key, index) in object" style="list-style-type:none">
{{ index + 1 }}. {{ key }} = {{ value }}
</li>
</div>
</ul>
</div>
Maybe so...
<ul v-for="(object,index) in objects"
:key="index">
{{index +1}}
<li v-for="(prop, index) in object" :key="index">
{{prop.author}}
{{prop.title}}
{{prop.publishedAt}}
</li>
</ul>
I've got input fields on one side of the page which is then displayed into boxes on the other side that actively shows what a user has inputted but in an organized way. I need to actively search the input fields for a specific string, in this case 'key' and then it would instantly change to a value stored in data. I've got a searchkeyword() function that should go through the array of objects where input fields are stored but haven't made it work just yet.
For example, if user types in 'key this is david' in input1 then it would change 'key' to it's stored value which is 'hello'. The value of key is also changing if a user clicks on other options. Really don't know where to go from here so any input helps :)
var app = new Vue({
el: '#app',
data: {
activeKeyword: 'HELLO',
inputs: [
{
input1: 'oranges',
input2: 'Online',
input3: 'Free'
}
]
},
methods: {
searchKeyword() {
for(var x = 0; x < this.ads.length; x++){
for(var input in this.inputs[x]){
if(this.ads[x] !== "boolean"){
this.ads[x][input] = String(this.inputs[x][input]).replace(/_keyword_/g, this.activeKeyword)
}
}
}
}
}
})
<link href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div class="box" v-for="(key, index) in inputs">
<div>
<span class="headline-ok">{{key.input1}} | </span>
<span class="headline-ok">{{key.input2}} | </span>
<span class="headline-ok">{{key.input3}}</span>
<br>
</div>
</div>
<div class="box" v-for="(key, index) in inputs">
<div class="form-inputs">
<label class="label is-capitalized">Input 1</label>
<div class="field">
<div class="control is-expanded">
<input class="input" type="text" v-model="key.input1">
</div>
</div>
</div>
<div class="form-inputs">
<label class="label is-capitalized">Headline Two </label>
<div class="field">
<div class="control is-expanded">
<input type="text" v-model="key.input2" class="input">
</div>
</div>
</div>
<div class="form-inputs">
<label class="label is-capitalized">Headline Three </label>
<div class="field">
<div class="control is-expanded">
<input type="text" v-model="key.input3" class="input">
</div>
</div>
</div>
</div>
</div>
Use a filter method to search for the matching substring of each input:
new Vue({
el: '#app',
filters: {
keyword(value, key, replacer) {
return (value && value.includes(key)) ? value.replace(key, replacer) : value
}
},
data() {
return {
replacer: 'Hello',
inputs: [{
key: 'foo',
model: null
},
{
key: 'bar',
model: null
},
{
key: 'baz',
model: null
}
],
demo: '',
demoString: 'Watch as blah is replaced with Hello'
}
},
mounted () {
let index = 0
setInterval(() => {
this.demo += this.demoString.charAt(index)
if (this.demo === this.demoString) {
this.demo = ''
index = 0
} else {
index++
}
}, 250)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<template v-for="(i, j) in inputs">
<label>Replace {{ i.key }} with {{ replacer }}</label>
<input v-model="i.model" :key="`input-${j}`">
<p :key="`p-${j}`">{{ i.model | keyword(i.key, replacer) }}</p>
</template>
<hr/>
<label>{{ this.demoString }}</label>
<input v-model="demo">
<p>{{ demo | keyword('blah', 'Hello') }}</p>
</div>
I want to duplicate a select element with the same values after a button click event. What is the best way to dynamically add a model for this duplicate so that the selected data keeps its 2-way binding? Also, when using a v-model will cause the first option not to be visible.
<section id="app">
selected jobs: {{preferredJobs.selectedJobs}}
<br><br>
<div class="form-row">
<div class="col-12">
<div class="form-group" v-for="(jobs, index) in preferredJobs.jobs">
<label for="preferred_function" v-if="index == 0">
Preferred job (multiple values possible) <br><br>
</label>
<select v-model="preferredJobs.selectedJobs">
<option value="">-- select --</option>
<option v-for="jobFunction in allJobs" :value="jobFunction.value">{{jobFunction.label}}</option>
</select>
<br><br>
</div>
</div>
</div>
<div class="form-row">
<div class="col-6">
<button type="button" #click="preferredJobs.jobs.push({jobs: allJobs})" class="btn btn-plus"><i class="fas fa-plus-circle"></i> Add Job</button>
</div>
<div class="col-6" v-if="itemsLength(preferredJobs.jobs) > 1">
<br>
<button type="button" #click="preferredJobs.jobs.pop()" class="btn btn-minus"><i class="fas fa-minus-circle"></i> Remove Job</button>
</div>
</div>
<script>
new Vue({
el: "#app",
data() {
return {
allJobs: [
{ value: 'job1', label: 'Job 1' },
{ value: 'job2', label: 'Job 2' },
{ value: 'job3', label: 'Job 3' },
{ value: 'job4', label: 'Job 4' },
{ value: 'job5', label: 'Job 5' },
],
preferredJobs: {
selectedJobs: [],
jobs: [
{
jobs: this.allJobs
},
],
},
}
},
methods: {
itemsLength(items){
return items.length;
},
},
})
You can do something like
v-model="data[dynamic_index]"
or you can use
<input :value="some_dynamic_variable" #input="$emit('input', $event.target.value)>