Vue v-for loop bind object key to select element - vuejs3

I have data like this - the keys for the phone object can be "mobile", "home"...
contacts[
11:{
name: "Mr Blobby"
phone: {
mobile: "07123 456789",
home: "0201 2345 6789"
}
...
}
...{}
Displaying it (cRud) is easy:
<div v-for="contact in contacts" :key="contact.id" :contact="contact">
<div v-for="(phone, type) in contact.phone" :key="type" :phone="phone">
<b>{{ type }}</b>
<h2>{{ phone }}</h2>
</div>
</div>
But how do I bind specifically the key (mobile/home...) using a select and v-model (CrUd) ?
<div v-for="(phone, index) in contact.phone" :key="phone">
<input type="tel" v-model.trim="contact.phone[index]" />
<select v-model="???">
<option value="mobile">Mobile</option>
option value="home">Home</option>
</select>
</div>

The code below should work if you want to iterate through the properties of the phone object. You can then bind the select value to a variable with v-model.
<select v-model="selectedPhone">
<option disabled value="">Select a phone</option>
<option
v-for="(value, name) in contact.phone"
:key="value"
:value="name"
>
{{ name }}
</option>
</select>
in v-for we provide the second argument 'name'(a.k.a. key) which will be 'mobile' or 'home' and then we set it as the options values.
So we set the phone object keys as the options values which i think is what you're aiming for?
You should also declare the initial value of the v-model variable inside the data option of your component.
data () {
return {
selectedPhone: ''
}
}

Related

Passing arguments to button onclick method in vuejs

I am trying to pass the selected values from the tag and pass it to a button’s click event. However, I was not able to get the data in the onclick function. See the code below.
I am getting undefined in the alert.
Please help.
<div class=“form-group”>
<div class=“form-group” align=“center”>
<label for=“select-Year”>Select CMS Fiscal Year :</label>
<select class=“form-control input-sm” style=“width:120px” id=“select-Year”>
<option v-for=“yr in years” value=“yr”>{{ yr }}</option>
</select>
</div>
<br/><br/>
<div class=“form-group” style=“align:center”>
<button id=“btnSubmit” class=“btn btn-primary” style=“align:center” v-on:click=“loadData(yr, $event)”>Open</button>
</div>
</div>
methods: {
`loadData`: function(yr, event){
alert(yr);
}
}
I tried to do this for you, go to the page and see <https://jsfiddle.net/Lr3psu2y/>.
Hope it with help for you.
The yr variable only exists within the scope of option when you used v-for on it.
That's why it's causing an error when you try to pass it to the event handler of your button which is located outside the scope of v-for.
How can I get selected option?
One way to get the year selected is to declare a year variable under your component data attribute and use the v-model directive on your select field to form a two-way binding.
data: function() {
return {
year: null
}
}
And in your select and button tags,
<select class="form-control input-sm" style="width:120px" id="select-Year" v-model="year">
<option v-for="yr in years" value="yr">{{ yr }}</option>
</select>
<button id="btnSubmit" class="btn btn-primary" style="align:center" v-on:click="loadData($event)">Open</button>
In this way, you can get access to the year in loadData,
loadData(event) {
console.log(this.year, event);
}

meteor onRendered not called

I’m trying to have a reactive bootstrap selectpicker but I have a weird behaviour:
An event has to change the options of the select but it works only after the first event which is not working because the app doesn’t go into the onRendered part…
This is the onRendered part:
var renderTimeout = false;
Template.printerselect.onRendered( function(){
if (renderTimeout !== false) {
Meteor.clearTimeout(renderTimeout);
}
renderTimeout = Meteor.setTimeout(function() {
$('#printerName').selectpicker("refresh");
renderTimeout = false;
}, 10);
});
Template.printerSetupForm.onRendered( function(){
$('.selectpicker').selectpicker();
});
here, the templates :
<div class="col-lg-3 col-md-4 col-xs-12 form-group">
<label>COMPANY</label>
<select id="printerCompany" class="form-control selectpicker" name="printer[company]">
<option selected="true" disabled="disabled" value={{company}}>
Please Select A Printer Company
</option>
{{#each Companies}}
<option value="{{company}}" {{printerCompanySelected company}}> {{company}}</option>
{{/each}}
</select>
</div>
<div class="col-lg-3 col-md-4 col-xs-12 form-group">
<label>PRINTER NAME</label>
<select id="printerName" class="form-control selectpicker" name="printer[name]">
<option selected="true" disabled="disabled" value={{name}}>
Please Select A Printer
</option>
{{#each Names}}
<!--<option value="{{name}}" {{printerNameSelected name}}>
{{name}}
</option>-->
{{>printerselect}}
{{/each}}
</select>
</div>
<template name="printerselect">
<option value="{{name}}"> {{name}} </option>
</template>
The refresh is called when the page is rendered.
Then I change the company which changes some Session variables and reactively to change the name select options but the refresh is not called so that doesn’t come to the onrendered part.
But when I change again the company it’s working, the onRendered part is called.
Weird thing is that even if this is not displaying the right names, when i’m choosing a name which doesn’t match with the company, the select chooses the right one.
Sorry for my english in advance, I did my best.
Thanks you in advance !
EDIT: Names helper :
Names: () => {
company=Session.get('printer').company;
if(typeof company!='undefined') {
return Printers.find({company: company}).fetch();
} else {
return Printers.find().fetch();
}
}
I set the Session variable 'printers' with an empty field. When I select a company, it's now working but without company, I don't get any printers because I don't have to test company with 'undefined' but with empty field.
So I changed to test with empty field and it isn't working anymore...
So weird that a test could cancel a onRendered, this must be an issue with the Mongo stuff.
I will continue to search on it.

How can I use autoform to populate a select element with #each?

Here is part of my form that I'd like to convert to using autoform.
<div class="col-lg-4 col-md-4 col-sm-4">
<label for="pay_with" id="pay_with_label">Pay With</label>
<select name="pay_with" id="pay_with" class="form-control select select-primary mbl" required data-placeholder="Select an Option">
<option value="Card">New Card</option>
<option value="Check">New Bank</option>
{{#each device}}
<option value="{{card_id}}" selected {{selected}}>{{brand}} - {{last4}}</option>
{{/each}}
</select>
In autoform, how do I translate this part?
{{#each device}}
<option value="{{card_id}}" selected {{selected}}>{{brand}} - {{last4}}</option>
{{/each}}
Create a template helper function that returns the options array for your select menu, by mapping your devices array and adding in the extra options in order to get the proper schema for autoform, like so:
Template.myForm.helpers({
deviceOptions: function() {
var deviceOpts = devices.map(function(device) {
return { label: device.brand+' - '+device.last4, value: device.card_id }
});
deviceOpts.unshift({ label: 'New bank', value: 'Check' });
deviceOpts.unshift({ label: 'New card', value: 'Card' });
return deviceOpts;
},
});
Then, you can call the helper in your template directive:
{{> afFieldInput name="payWith" type="select" options=deviceOptions }}

How do I indicate 'checked' or 'selected' state for input controls in Meteor (with spacebars templates)?

So I'm trying to be efficient and clean in my Spacebars templates as I work with Meteor. But I'm stumped by the way in which checkboxes and select options are to be dealt with. Suppose I want to have a checkbox set as checked or not depending on a flag that is in a document in one of my collections. I don't appear to be able to do the following:
<input type='checkbox' id='item-{{this.item_id}}' {{#if checked}}checked{{/if}} />
When I try this, I get the following error:
A template tag of type BLOCKOPEN is not allowed here.
If I try the following options, though, they all result in the checkbox being checked even when the flag is false:
<input type='checkbox' id='item-{{this.item_id}}' checked='{{#if checked}}true{{/if}}' />
<input type='checkbox' id='item-{{this.item_id}}' checked='{{#if checked}}true{{else}}false{{/if}}' />
I have the same trouble with selected in my select options, so I end up doing something like the following to get around it, which seems verbose and error-prone:
<select id='option-{{this.item_id}}'>
{{#if option_60}}
<option value='60' selected>1 hour</option>
{{else}}
<option value='60'>1 hour</option>
{{/if}}
{{#if option_90}}
<option value='90' selected>90 mins</option>
{{else}}
<option value='90'>90 mins</option>
{{/if}}
{{#if option_120}}
<option value='120' selected>2 hours</option>
{{else}}
<option value='120'>2 hours</option>
{{/if}}
</select>
You can use non-block helpers for placing such arguments:
UI.registerHelper('checkedIf', function(val) {
return val ? 'checked' : '';
});
<input type="checkbox" {{checkedIf checked}}>
Here is an example of the code I use to solve this problem, this should be pretty straightforward.
JS
Template.myTemplate.helpers({
checked:function(){
// assumes that this.checked is the flag in your collection
return this.checked?"checked":"";
},
options:function(){
// store options in a helper to iterate over in the template
// could even use http://momentjs.com/docs/#/durations/humanize/ in this case ?
return [{
value:60,
text:"1 hour"
},{
value:90,
text:"90 mins"
},{
value:120,
text:"2 hours"
}];
},
selected:function(value){
// compare the current option value (this.value) with the parameter
// the parameter is the value from the collection in this case
return this.value==value?"selected":"";
}
});
Template.parent.helpers({
dataContext:function(){
// dummy data, should come from a collection in a real application
return {
checked:true,
value:90
};
}
});
HTML
<template name="myTemplate">
<input type="checkbox" {{checked}}>
<select>
{{#each options}}
{{! ../ syntax is used to access the parent data context which is the collection}}
<option value="{{value}}" {{selected ../value}}>{{text}}</option>
{{/each}}
</select>
</template>
<template name="parent">
{{> myTemplate dataContext}}
</template>
EDIT : using universal helpers as Hubert OG hinted at :
JS
Template.registerHelper("checkedIf",function(value){
return value?"checked":"";
});
Template.registerHelper("selectedIfEquals",function(left,right){
return left==right?"selected":"";
});
HTML
<template name="myTemplate">
<input type="checkbox" {{checkedIf checked}}>
<select>
{{#each options}}
<option value="{{value}}" {{selectedIfEquals value ../value}}>{{text}}</option>
{{/each}}
</select>
</template>
The best, most efficient and effective way to accomplish this is to setup global template helpers, one each for determining checked and selected values. For documentation on creating global template helpers, see this documentation.
For checked, I suggest implementing it in this way:
Template.registerHelper('isChecked', function(someValue) {
return someValue ? 'checked' : '';
});
For selected, I suggest implementing it in this way:
Template.registerHelper('isSelected', function(someValue) {
return someValue ? 'selected' : '';
});
With these two global template helpers implemented, you can use them in any of your templates within your application like this:
<template name="someTemplate">
<input type="checkbox" {{isChecked someValue}}>
<select>
{{#each someOptions}}
<option {{isSelected someValue}}>{{someDisplayValue}}</option>
{{/each}}
</select>
</template>

Setting the selected value of a Select element in Handlebars

I have a handlebars template that I am embedding in my html page. There is a select element with all of the available options already rendered. How can I set the selected value of the select list when I render my template?
<script id="my-template" type="text/x-handlebars-template">
<div id="my-modal">
<form action="/TestAction" method="post">
<input id="MyId" name="MyId" type="hidden" value="{{MyId}}" />
<label for="Test">Test: (optional)</label>
<select id="Test" name="Test">
<option value="">-- Choose Test --</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</form>
</div>
</script>
If you don't want to build out the option as part of the helper, you can use a combination of a small custom handlebars helper and parent context, denoted using the ../ syntax:
First write the helper:
Handlebars.registerHelper('selected', function(option, value){
if (option === value) {
return ' selected';
} else {
return ''
}
});
And then in your template you call your helper and pass in the parent context inside the each loop to check for selectedState
{{#each states}}
<option value="{{this}}" {{selected this ../selectedState}}>{{this}}</option>
{{/each}}
I took the {{#each}} helper as inspiration, and wrote a custom helper that does the same thing: loops over a list, and continually appends the contents of the arguments to an output string. (From here: Handlebars block helpers)
In this case, I'm not passing in a chunk of template HTML to serve as the function's options parameter, like you would when using {{#each}}. Instead I am just building up the <option>
tags by brute force, and testing every iteration of the context list. Lastly, I return a big long string of <option></option> tags, and hopefully one of them has selected="selected".
The function:
Handlebars.registerHelper('options_selected', function(context, test) {
var ret = '';
for (var i = 0, len = context.length; i < len; i++) {
var option = '<option value="' + context[i]+'"';
if (test.toLowerCase() == context[i].toLowerCase()) {
option += ' selected="selected"';
}
option += '>'+ Handlebars.Utils.escapeExpression(context[i]) + '</option>';
ret += option;
}
return new Handlebars.SafeString(ret);
});
The tag in use:
<script id="form-state" type="text/x-handlebars-template">
<select name="state">
{{{options_selected states selectedState}}}
</select>
</script>
Please suggest any edits that would improve this, thanks!
You can use values straight in the Handlebars template like so.
Handlebars Template
<select id="distance">
<option value="15" {{#if (isEqual 15 distance)}} selected {{/if}}>15</option>
<option value="25" {{#if (isEqual 25 distance)}} selected {{/if}}>25</option>
<option value="50" {{#if (isEqual 50 distance)}} selected {{/if}}>50</option>
<option value="100" {{#if (isEqual 100 distance)}} selected {{/if}}>100</option>
<option value="300" {{#if (isEqual 300 distance)}} selected {{/if}}>300</option>
</select>
Handlebars Helper
define(['hbs/handlebars'], function (Handlebars) {
'use strict';
Handlebars.registerHelper('isEqual', function (expectedValue, value) {
return value === expectedValue;
});
});
Here is a solution (built over EmberJS to ease the JS part)
I refactored your sample a little, to have objects for proposed values, which can by the way carry the selected attribute...
The template part:
<script type="text/x-handlebars" data-template-name="my-template">
<div id="my-modal">
<form action="/TestAction" method="post">
<input id="MyId" name="MyId" type="hidden" value="{{MyId}}" />
<label for="Test">Test: (optional)</label>
<select id="Test" name="Test">
<option value="">-- Choose Test --</option>
{{#each values}}
<option {{bindAttr value="id" selected="selected"}}>{{label}}</option>
{{/each}}
</select>
</form>
</div>
</script>
The JS part:
App.MyView = Ember.View.extend
templateName: 'my-template'
MyId: 42
values: [{
id: 1,
label: '1'
}, {
id: 2,
label: '2'
}, {
id: 3,
label: '3',
selected: true
}, {
id: 4,
label: '4'
}]
You can try it # http://jsfiddle.net/MikeAski/uRUc3/
I had same problem.
$('select').val(value);
This is how I solved it, I set the desired value with jQuery after rendering the template. Was surprisingly easy. (Maybe its also a way to keep the templates logicless)

Resources