Ember - get state of multiple checkboxes one by one - javascript

I am working on an Ember app (version 1.11, old one) and have multiple checkboxes build over in loop, code as below.
I need to know if an element has been checked or unchecked in action.
Ember ehbs:
{{#each item in data}}
<label>
<input type="checkbox" checked="isChecked" {{action "getData" item on="change"}}/>
<span>{{item.type}}</span>
</label>
{{/each}}
Ember Component:
var component = Ember.Component.extend({
isChecked: true,
actions: {
getData: function(data){
var state = this.get('isChecked');
var type = data.type;
}
}
})
I thought the variable's "isChecked" value will be maintained for each individual checkbox, but its not the case, it is just one variable for all checkboxes.
So, how can I achieve this OR check individual states for all checkboxes whether its checked or unchecked.
In long run, I am trying to get here - http://emberjs.jsbin.com/qaruviwuze/edit?html,js,output but dont want to access and play with DOM as its done here.

make each checkbox as component
<input type="checkbox" checked="isChecked" {{action "getData" item on="change"}}/>
as follows checkbox-component
{{#each model as |item|}}
{{checkbox-component isChecked=item.isCheked}}
{{/each}}
such that you can retrieve easily each check item value.
export default Ember.Component.extend({
tagName: "input",
isChecked: false,
attributeBindings: ['type', 'checked'],
type: 'checkbox',
checked: function() {
return this.get('isChecked');
}.property('isChecked'),
click: function() {
console.log(this.set('checked', this.$().prop('checked')))
}
});
check https://ember-twiddle.com/996f6408266af8cd4d3372bed8e8331c?openFiles=components.checkbox-component.js%2Ctemplates.components.checkbox-component.hbs

Related

How to pass/delete array params in HTTP Params with Angular

I have an Array of statuses objects. Every status has a name, and a boolean set at false by default.
It represent checkbox in a form with filters, when a checkbox is checked bool is set at true :
const filters.statuses = [
{
name: "pending",
value: false
},
{
name: "done",
value: false
},
];
I am using Angular HTTP Params to pass params at the URL.
filters.statuses.forEach((status) => {
if (status.value) {
this.urlParams = this.urlParams.append('statuses[]', status.name);
}
});
Url params looks like when a status is checked :
&statuses%5B%5D=pending
My problem is when I want to unchecked.
I know HTTP Params is Immutable, so, I'm trying to delete the param when checkbox is unchecked, so set to false :
...else {
this.urlParams = this.urlParams.delete('statuses');
}
But, it not works, URL doesn't change.
And if I re-check to true after that, the URL looks like :
&statuses%5B%5D=pending&statuses%5B%5D=pending
How can I delete params, if the status value is false, and keep others statuses in URL ?
Project on Angular 10.
Thanks for the help.
UPDATE : It works to delete, my param name was not good :
else {
this.urlParams = this.urlParams.delete('statuses[]', status.name);
}
But, my other problem, it's when I check 2 or more checkbox, the append function write on URL : &statuses%5B%5D=pending&statuses%5B%5D=pending&statuses%5B%5D=done
I have prepared an example to try to answer your question (If I understand this right way).
You can change the checkboxes state or the URL to play with it. Also, I added helper buttons, which will navigate you to different cases (by changing the URL).
Here is the example: https://stackblitz.com/edit/angular-router-basic-example-cffkwu?file=app/views/home/home.component.ts
There are some parts. We will talk about HomeComponent.
You have ngFor which displays statuses, I handled state using ngModel (you can choose whatever you want).
You have a subscription to the activatedRoute.queryParams observable, this is how you get params and set up checkboxes (the model of the checkboxes)
You have the ngModelChange handler, this is how you change the route according to the checkboxes state
Let's focus on 2 & 3 items.
The second one. Rendering the correct state according to the route query params. Here is the code:
ngOnInit() {
this.sub = this.activatedRoute.queryParams.subscribe((params) => {
const statusesFromParams = params?.statuses || [];
this.statuses = this.statuses.map((status) => {
if (statusesFromParams.includes(status.name)) {
return {
name: status.name,
active: true,
};
}
return {
name: status.name,
active: false,
};
});
});
}
Here I parse the statuses queryParam and I set up the statuses model. I decide which is active and which is not here.
The third one. You need to update the URL according to the checkboxes state. Here is the code:
// HTML
<ng-container *ngFor="let status of statuses">
{{ status.name}} <input type="checkbox" [(ngModel)]="status.active" (ngModelChange)="onInputChange()" /> <br />
</ng-container>
// TypeScript
onInputChange() {
this.router.navigate(['./'], {
relativeTo: this.activatedRoute,
queryParams: {
statuses: this.statuses
.filter((status) => status.active)
.map((status) => status.name),
},
});
}
Here you have the ngModelChange handler. When any checkbox is checked/unchecked this handler is invoked. In the handler, I use the navigate method of the Router to change the URL. I collect actual checkboxes state and build the query parameters for the navigation event.
So, now you have a binding of the checkboxes state to the URL and vice versa. Hope this helps.

Polymer 3: How to implement two way data binding for radio input

I'm trying to understand/implement two way attribute binding in a Polymer 3 web component. I've got the following code:
import {html, PolymerElement} from '#polymer/polymer/polymer-element.js';
class CustomInputComponent extends PolymerElement {
static get template() {
return html`
<div>
<template is="dom-repeat" items="{{ratings}}">
<input type="radio"
name="group"
id="item_{{item.id}}"
value="{{item.checked}}"
checked$="{{item.checked}}">
</template>
</div>`;
}
static get properties() {
return {
ratings: {
type: Array,
value: [
{ id: 1, checked: true },
{ id: 2, checked: false }
]
}
};
}
}
window.customElements.define('custom-input-component', CustomInputComponent);
As you can see, I have defined a Array property containing a default list of values. This property is a model from which I want to render a radio group. The initial state looks good. But when I click on the unchecked input, the DOM elements don't update correctly.
I'd bet I'm missing something really simple...
The main things are:
You are binding to the checked attribute ($=), however I don't think radio inputs dynamically update their checked attribute. AFAICT, the checked property is what changes when the input gets selected.
Also, native <input type="radio"> inputs will only fire their change and input events when they are selected, not when they are de-selected. Polymer relies on events to trigger property effects like data bindings; this means that an upwards data binding (from the input to your custom element) will only get processed when the checked property on an input changes from false to true. Effectively, once ratings[n].checked becomes true, it will never be made false because Polymer has no way to know that this has occurred.
Incidentally, to perform two-way binding on a native HTML element, you would also need to include an annotation for the event that the radio input fires when it is selected. So if you did want to capture the changes on selection, it'd be something like checked="{{item.checked::change}}".
A couple of options:
Use paper-radio-buttons inside a paper-radio-group instead of native <input>s. These elements behave well for two-way data binding.
Listen for the change when a new item gets checked, and manually update ratings[n].checked to false for the previously selected item.
A couple more things about your code
(I don't think this is anything to do with your current problem, but it will help avoid future problems) when initializing a default value for an object or array property in a Polymer element, remember to use a function so that each element instance gets its own unique array or object. E.g.:
ratings: {
type: Array,
value: function(){
return [
{ id: 1, checked: true },
{ id: 2, checked: false }
];
}
}
Normally I think, you wouldn't want to change the values of your radio inputs. Conventionally, when the <form> containing a radio input group is submitted, the value on the radio input that is currently checked gets included with the form data, and the other radio input values are ignored. Here's an example on W3Schools. So instead of value="{{item.checked}}", something like value="[[item.data]]".
So the whole thing might be something like
class CustomInputComponent extends PolymerElement {
static get properties () {
return {
ratings: {
type: Array,
value: function(){
return [
{ id: 1, checked: true, value: 'pie' },
{ id: 2, checked: false, value: 'fries' },
{ id: 3, checked: false, value: 'los dos' }
];
}
},
selected: {
// type: Number or Object, idk
// Keep track of the selected <input>
}
};
}
static get template() {
return html`
<p>do you want pie or fries?</p>
<div id="mydiv">
<template is="dom-repeat" items="{{ratings}}">
<input
type="radio"
name="testgroup"
id="[[item.id]]"
value="[[item.value]]"
checked="{{item.checked::input}}"
on-change="radioChanged"
>[[item.value]]
</input>
</template>
</div>
`;
}
radioChanged(event){
// update ratings[n].checked for selected input
// set selected input to currently selected input
}
}

Checkbox form array data Vue 2

I have a checkbox list which is generated using a for loop that consists of an id and a name:
Data:
yards[{id:1,name:'test'}] etc
HTML:
<ul class="checkbox-list">
<template v-for="(yard, index) in yards">
<li>
<input type="checkbox"
v-bind:id="'yardlist_'+yard.name"
v-bind:value="yard.id"
v-model="newSchedule.yards.id">
<label v-bind:for="'yardlist_'+yard.name">{{ yard.name }}</label>
</li>
<li>
<input type="text"
class="form-control"
placeholder="Yard notes..."
v-model="newSchedule.yards.notes">
</li>
</template>
</ul>
I want to save the selected checkbox with the id and notes field in an array:
newSchedule: {
due_at: '',
notes: '',
users: [],
yards: [{id:'',notes:'']
}
I have tried using the index from the yards array: newSchedule.yards[index].notes but am getting the following error "TypeError: undefined is not an object (evaluating 'newSchedule.yards[index].id')"
Any ideas how I can achieve this?
** Update **
Here is a basic fiddle of what I am wanting to achieve:
https://jsfiddle.net/j7mxe5p2/13/
I think you are trying to mix the old jQuery or javascript way of doing things with Vue framework. You should not have to set id on <input> elements to capture or set its value.
The correct way to do this is as follows:
new Vue({
el: '#app',
data: function() {
return {
yards: [
{id: 1, name: 'test', selected: true},
{id: 2,name: 'test 2', selected: false},
{id: 3,name: 'test 3', selected: false},
{id: 4,name: 'test 4', selected: true}
]
};
},
template: `
<div class="list-of-yards"> <!-- You cannot use v-for on the top-level element -->
<label for="jack" v-for="yard in yards">
<input type="checkbox" v-model="yard.selected"> {{yard.name}}
</label>
</div>
`,
});
Here is a jsFiddle of the above code: https://jsfiddle.net/z48thf9a/
Things to note:
You cannot use v-for on the template tag itself
You cannot use v-for on the top-level element just inside template. The template should contain one and only enclosing element, typically a <div>
There is no need to set id on input elements. You need to use v-model for your model-view bindings
If you still have issues, please provide a jsFiddle to debug further.
Edited after comment #1 and #2:
My above response is focused more on constructing the Vue component and rendering the list with proper binding to the checkboxes.
To get the checked items into a separate array, you can use a computed property in the same component to run through the original array this.yards and create a new array of selected items only.
Here is the jsFiddle for capturing the checked values: https://jsfiddle.net/z48thf9a/1/
You may modify the above to capture only the id part, and rename selectedYards to newSchedule or whatever your app requires.
I am not sure if I understood your question correctly, and if this solves your issue. Can you please provide more code samples?

How to use Ember query parameters with beforeModel and select?

Demo: http://jsbin.com/zexopa/1/edit?html,js,output
I use the query parameters in my application. And the queryParameters are 'name' and 'category'.
The 'name' parameter is used in the select and the 'category' uses the input, but there is something wrong with the select 'name' if I set it default to null.
If I change the 'name', the 'name' always is undefined in the url.
Route:
App.IndexRoute = Ember.Route.extend({
beforeModel: function() {
this.controllerFor('index').set('products', [1,2,3]);
},
model: function() {
return [{'is_active':false, 'name':'One'}, {'is_active':false, 'name':'Two'}, {'is_active':false, 'name':'Three'}, {'is_active':false, 'name':'Four'},{'is_active':false, 'name':'Five'}];
},
actions: {
queryParamsDidChange: function() {
this.refresh();
}
}
});
Controller:
App.IndexController = Ember.Controller.extend({
queryParams: ['name', 'category'],
name: null,
category: null
});
Template:
<script type="text/x-handlebars">
<h2>Welcome to Ember.js</h2>
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="index">
{{view "select" content=products value=name prompt="all"}}
{{input type="text" value=category class="form-control"}}
<ul>
{{#each model as |item|}}
<li>{{item.name}}</li>
{{/each}}
</ul>
</script>
Can you help to check what happens to my application?
Query params must be string to be properly binded. Your input works, as the value is String object. In name array you provided Integer. Unfortunately, I have not found any mention about that in docs, but you can see a working demo here: http://jsbin.com/lixili/1/edit?html,js,output
If I can give you some tip about your code:
beforeModel is not a place for setting controller properties, do it in setupController method as in JSBin provided
You did not defined query params in route, but you could and get rid of the queryParamsDidChange
Hope I helped!

How to affect state of ObjectController from its ArrayController in ember.js

I am still trying to understand how to properly structure an ember.js application. So, this may be a systemic issue with the way I am trying to solve this. That being said, I am going to try asking the same question a couple different ways ...
In the code example below, when a record is created, how can I get it to be added to the list with the isEditing property set to true?
Can I access to a specific object controller from its array controller?
Each task has a view state and an edit state. When a new task is created, how can I have it initially appear in the edit state?
App.TasksController = Ember.ArrayController.extend({
actions: {
createTask: function(){
var task = this.store.createRecord('task');
task.save();
}
}
});
App.TaskController = Ember.ObjectController.extend({
isEditing: false,
actions: {
toggleEditing: function(task) {
if(this.isEditing){
task.save();
}
this.set('isEditing', ! this.isEditing );
}
}
});
<script type="text/x-handlebars" data-template-name="tasks">
<ul>
{{#each task in controller}}
{{render "task" task}}
{{/each}}
<li {{action "createTask"}} >
New Task
</li>
</ul>
</script>
<script type="text/x-handlebars" data-template-name="task">
<li {{action "toggleEditing" task on="doubleClick"}} >
{{#if isEditing }}
{{textarea value=title cols="80" rows="6"}}
{{else}}
{{title}}
{{/if}}
</li>
</script>
Set the property on the model.
You don't have to define the property as an attr on the model (which means it won't send it up to the server on save etc), but you can set the property on the model.
Or you can do it based on the currentState of the model. (click go to orders, then add orders)
http://emberjs.jsbin.com/AvOYIwE/4/edit
App.OrderController = Em.ObjectController.extend({
_editing: false,
editing: function(){
return this.get('_editing') || (this.get('model.currentState.stateName') == 'root.loaded.created.uncommitted');
}.property('model.currentState.stateName', '_editing'),
actions: {
stopEditing: function(){
// blow away the computed property and just set it to true
this.set('editing', false);
},
startEditing: function(){
this.set('editing', true);
},
}
});

Categories

Resources