How can i dynamically add an Input select element on click of a button in ember - dom

Am creating an ember application where am in need of dynamicaly adding a select element which will have options fetched from a server. so the select elements look like this. And instead of having all dropdown boxes predefined i need to add them dynamicaly like on a click of a button like( + add more). like
and each of those drop down boxes should contain the datas that is fetched from the server. plus i need a way to get the datas from those dynamically created select fields.
my .hbs for the current drop down page is..
map.hbs
<center><h4>Map</h4></center>
<container class = "cond">
{{#each this.model.sf as |row|}}
<select class = "sel">
{{#each this.model.sf as |sf|}}
<option value = {{sf.attrname}}>{{sf.attrname}}</option>
{{/each}}
</select><br>
{{/each}}
I tried ember-dynamic-fields but its depracted and I couldnt able to use it.. and all other solutions on web or for ember way older versions.. nothing works on ember 4.6 so could anyone helpout?

Using The Platform's native FormData functionality, demo'd here.
I think we can generate any number of inputs based on input data in the following way:
Store the form's state in some variable
conditionally show further select / inputs based on the properties in that form state.
Code-wise, that'd look like this:
{{#if (dataHasValueFor "fieldName")}}
Show previously hidden field
{{/if}}
And of course the devil is in the implementation details, so, a full working example (with sample data I made up -- we can iterate on this if you want for your specific data set, just leave a comment on this post/answer).
import Component from '#glimmer/component';
import { tracked } from '#glimmer/tracking';
import { on } from '#ember/modifier';
import { get } from '#ember/helper';
// This could be your model data from your route
const DATA = {
fruits: [
'apple', 'banana', 'orange', 'mango',
'watermellon', 'avacado', 'tomato?'
],
veggies: ['cocumber', 'tomato?', 'green bean', 'kale', 'spinach'],
peppers: ['carolina reaper', 'habanero', 'jalapeƱo']
}
export default class Demo extends Component {
#tracked formData;
get categories() {
return Object.keys(DATA);
}
handleInput = (event) => {
let formData = new FormData(event.currentTarget);
let data = Object.fromEntries(formData.entries());
this.formData = data;
}
handleSubmit = (event) => {
event.preventDefault();
handleInput(event);
}
isSelected = (name, value) => this.formData?.[name] === value;
<template>
<form
{{on 'input' this.handleInput}}
{{on 'submit' this.handleSubmit}}
>
<label>
Food Category<br>
<select name="category" placeholder="Select...">
<option selected disabled>Select a food group</option>
{{#each this.categories as |name|}}
<option
value={{name}}
selected={{this.isSelected "category" name}}
>
{{name}}
</option>
{{/each}}
</select>
</label>
<hr>
{{#let (get this.formData "category") as |selectedCategory|}}
{{#if selectedCategory}}
<label>
{{selectedCategory}}<br>
<select name={{selectedCategory}}>
<option selected disabled>
Select {{selectedCategory}}
</option>
{{#each (get DATA selectedCategory) as |food|}}
<option
value={{food}}
selected={{this.isSelected selectedCategory food}}
>
{{food}}
</option>
{{/each}}
</select>
</label>
{{/if}}
{{/let}}
</form>
<hr>
FormData:
<pre>{{toJson this.formData}}</pre>
</template>
}
const toJson = (input) => JSON.stringify(input, null, 4);
This demo is interactive here, on limber.glimdown.com
Note that the syntax used here is what will be default in the upcoming Polaris Edition of Ember, and is available via ember-template-imports
Update (after comments)
Demo here
I took some liberties with the how the fields are dynamic, because I think this more easily shows the concept asked about in the question: dynamically showing fields in a form.
import Component from '#glimmer/component';
import { tracked } from '#glimmer/tracking';
import { on } from '#ember/modifier';
import { get } from '#ember/helper';
export default class Demo extends Component {
#tracked formData;
handleInput = (event) => {
let formData = new FormData(event.currentTarget);
let data = Object.fromEntries(formData.entries());
this.formData = data;
}
handleSubmit = (event) => {
event.preventDefault();
handleInput(event);
}
<template>
<form
{{on 'input' this.handleInput}}
{{on 'submit' this.handleSubmit}}
>
<div class="grid">
<label>
Name <input type="checkbox" name='hasName'>
</label>
<label>
Email <input type="checkbox" name='hasEmail'>
</label>
<label>
Alias <input type="checkbox" name='hasAlias'>
</label>
<hr>
{{#if (get this.formData 'hasName')}}
<label>
Name
<input type="text" name="name" class="border" />
</label>
{{/if}}
{{#if (get this.formData 'hasEmail')}}
<label>
Email
<input type="email" name="email" class="border" />
</label>
{{/if}}
{{#if (get this.formData 'hasAlias')}}
<label>
Alias
<input type="text" name="alias" class="border" />
</label>
{{/if}}
</div>
</form>
<hr>
FormData:
<pre>{{toJson this.formData}}</pre>
</template>
}
const toJson = (input) => JSON.stringify(input, null, 4);
And... since it seems you have a lot of fields, you may want to go as dynamic as possible:
demo here
which is the following code:
<form
{{on 'input' this.handleInput}}
{{on 'submit' this.handleSubmit}}
>
<div class="grid">
{{#each FIELDS as |field|}}
<label>
{{field}} <input type="checkbox" name='has-{{field}}'>
</label>
{{/each}}
<hr>
{{#each FIELDS as |field|}}
{{#if (get this.formData (concat 'has-' field))}}
<label>
{{field}}
<input type="text" name={{field}} class="border" />
</label>
{{/if}}
{{/each}}
</div>
</form>

I guess Simple js code did the magic of adding and retriving data.. pity of me after finding out.. And for some dynamic ember formdata the previous answer from nullvox helped out.. so here is the code
.hbs
<table class="table">
<th>
<td>Sf</td>
</th>
<th>
<td>Db</td>
</th>
<tbody id = "map">
</tbody>
</table>
<button class = "btn btn-sm btn-primary" type="button" {{action "submit"}}>Submit</button>
<button class = "btn btn-success btn-sm" onclick = {{action "get"}} type="button">Add another</button>
controller code for creating element
#action
get() {
let div = document.getElementById('map');
let tr = document.createElement('tr');
let td = document.createElement('td');
let td2 = document.createElement('td');
var select = document.createElement('select');
select.setAttribute('class', 'sfselect');
div.appendChild(tr);
tr.appendChild(td);
td.appendChild(select);
for (var i = 0; i < sf.length; i++) {
var option = document.createElement('option');
option.value = sf[i];
option.text = sf[i];
select.appendChild(option);
}
var select2 = document.createElement('select');
select2.setAttribute('class', 'dbselect');
tr.appendChild(td2);
td2.appendChild(select2);
for (var i = 0; i < db.length; i++) {
var option = document.createElement('option');
option.value = db[i];
option.text = db[i];
select2.appendChild(option);
}
}
controller code for getting data
#action submit() {
var sfattr = document.querySelectorAll('.sfselect');
var dbattr = document.querySelectorAll('.dbselect');
var sf = [];
var db = [];
console.log(sfattr.length);
let datas;
for (var i = 0; i < sfattr.length; i++) {
sf[i] = sfattr[i].value;
db[i] = dbattr[i].value;
}
let m1 = sf.toString();
let m2 = db.toString();
$.ajax({
url: 'http://localhost:8080/lorduoauth/Map',
method: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: {
m1: m1,
m2: m2,
},
success: function (response) {
console.log(datas);
alert(response);
},
error: function (xhr, status, error) {
var errorMessage = xhr.status + ': ' + xhr.statusText;
alert('error' + errorMessage);
},
});
}
thus the output looks like this

Related

How to change text inputs into tags, in an existing Vue 3 form, using a Tag Input Component?

I have an existing form in a Vue 3 project that posts successfully to a Cloud Firestore database.
How do I use change two of the type="text" input fields into tag inputs, using a Tag Input Component like this? Here's a link to it on CodeSandbox
The standalone tutorial is very clear and works fine. What I'm struggling with is how to incorporate that into an existing Vue 3 form and continue posting everything to the Firestore database.
I stripped-away styles and many other input fields from the "base" code below:
<template>
<form #submit.prevent="handleSubmit" >
<h3>What kind of pet?</h3>
<div class="space-y-0">
<select required name="pet_type" id="pet_type" v-model="pet_type">
<option value="">Please select</option>
<option value="cat">Cat</option>
<option value="dog">Dog</option>
<option value="wolverine">Wolverine</option>
</select>
</div>
<hr>
<div> <!-- Want to change this into the first tag input -->
<h3>Pros</h3>
<div for="petPros">What are 3 positive things about this pet?</div>
<input type="text" placeholder="separate , with , commas" id="petPros" v-model="petPros">
<label for="petPros">separate , with , commas</label>
</div>
<hr>
<div>
<h3>Cons</h3> <!-- Want to change this into a second tag input -->
<div for="petCons">And what are 3 negative things about this pet?</div>
<input type="text" placeholder="separate , with , commas" id="petPros" v-model="petCons">
<label for="petCons">separate , with , commas</label>
</div>
<hr>
<h3>Privacy</h3>
<div>
<div>
<input type="radio" id="Fullpublic" value="Fullpublic" name="reviewPrivacy" required v-model="reviewPrivacy">
<label class="text-base inline-flex ml-4 align-bottom" for="Fullpublic">Public</label>
</div>
<div>
<input type="radio" id="keepFullyPrivate" value="keepFullyPrivate" name="reviewPrivacy" required v-model="reviewPrivacy">
<label class="text-base inline-flex ml-4 align-bottom" for="keepFullyPrivate">Private</label>
</div>
</div>
<hr>
<button v-if="!isPending" >Submit</button>
<button v-else disabled>Saving...</button>
</form>
</template>
<script>
import { ref } from 'vue'
import useStorage from '#/composables/useStorage'
import useCollection from '#/composables/useCollection'
export default {
setup() {
const { filePath, url, uploadImage } = useStorage()
const { error, addDoc } = useCollection('reviews')
const { user } = getUser()
const router = useRouter()
const pet_type = ref('')
const petPros = ref('')
const petCons = ref('')
const reviewPrivacy = ref('')
const file = ref(null)
const fileError = ref(null)
const isPending = ref(false)
const handleSubmit = async () => {
if (file.value) {
isPending.value = true
await uploadImage(file.value)
const res = await addDoc({
pet_type: pet_type.value,
petPros: petPros.value,
petCons: petCons.value,
reviewPrivacy: reviewPrivacy.value,
userId: user.value.uid,
userName: user.value.displayName,
createdAt: timestamp()
})
isPending.value = false
if (!error.value) {
router.push({ name: 'ReviewDetails', params: { id: res.id }})
}
}
}
// allowed file types
const types = ['image/png', 'image/jpeg']
const handleChange = (e) => {
let selected = e.target.files[0]
console.log(selected)
if (selected && types.includes(selected.type)) {
file.value = selected
fileError.value = null
} else {
file.value = null
fileError.value = 'Please select an image file (png, jpg or jpeg)'
}
}
return { pet_type, petPros, petCons, reviewPrivacy, handleSubmit, fileError, handleChange, isPending }
}
}
</script>
<style>
</style>
Thanks for any help!
In the form, replace the two <input type="text">s with <TagInput>. Keep the v-model the same, as TabInput implements v-model.
<!-- BEFORE -->
<input type="text" placeholder="separate , with , commas" id="petPros" v-model="petPros">
<input type="text" placeholder="separate , with , commas" id="petPros" v-model="petCons">
<!-- AFTER -->
<TagInput id="petPros" v-model="petPros" />
<TagInput id="petCons" v-model="petCons" />
Locally register TagInput.vue in the form component:
import TagInput from "./TagInput.vue";
export default {
components: {
TagInput,
},
}
Change the initial values of petPros and petCons refs to arrays, as the TabInput outputs a string array of the input tag values:
// BEFORE
const petPros = ref('')
const petCons = ref('')
// AFTER
const petPros = ref([])
const petCons = ref([])
TabInput normally adds a tag upon hitting TAB, but your placeholder suggests that you want to use the comma key , instead. To do that, update the modifier in the #keydown binding:
<!-- BEFORE -->
<input v-model="newTag"
#keydown.prevent.tab="addTag(newTag)"
>
<!-- AFTER -->
<input v-model="newTag"
#keydown.prevent.,="addTag(newTag)"
>
demo

Angular 2 Template Driven Forms - Array Input Elements

I have been struggling for 1 and half day and still couldn't find any solution to the problem. I am working on simple form which has select and checkboxes element.When I try submitting the form I do not get the values of select and checkboxes but rather I just get true in the console.
I am working on template driven form.
<form (ngSubmit)="addSubcontractor(subcontractorForm)" #subcontractorForm="ngForm">
<h5>Type :</h5>
<div class="form-group">
<div *ngFor="let contractor_type of contractor_types;let i = index;" class="pull-left margin-right">
<label htmlFor="{{ contractor_type | lowercase }}">
{{ contractor_type }} :
</label>
<input type="checkbox" name="_contractor_type[{{i}}]" [value]="contractor_type" ngModel>
</div>
<div class="form-group">
<select class="form-control costcodelist" name="_cc_id[]" multiple="true" ngModel>
//When I put ngModel on select I just keep getting error
//TypeError: values.map is not a function
<option *ngFor="let costcode of costcodes" [selected]="costcode.id == -1" [value]="costcode.id">{{ costcode.costcode_description }}</option>
</select>
</div>
</form>
Component Section
export class SubcontractorComponent implements OnInit, OnDestroy {
private contractor_types = ['Subcontractor', 'Supplier', 'Bank', 'Utility'];
constructor(private costcodeService: CostcodeService,
private subcontractorService: SubcontractorService) {
this.subcontractorService.initializeServices();
}
ngOnInit() {
this.costcode_subscription = this.costcodeService.getAll()
.subscribe(
(costcodes) => {
this.costcodes = costcodes;
});
}
addSubcontractor(form: NgForm) {
console.log(form.value);
}
}
When I remove ngModel from select element the code runs fine and When I submit the form I get the following output.
_contractor_type[0]:true
_contractor_type[1]:true
_contractor_type[2]:true
_contractor_type[3]:""
I do not get the checkboxes values as well the selected options from select element.
Your comments and answer will appreciated a lot.
Thanks
Here is a simple selection that i use with my Template driven form.
<form #f="ngForm" (submit)="addOperator(f.valid)" novalidate>
<label>Name</label>
<input [(ngModel)]="operator.name" name="name">
<label >Service</label>
<select #service="ngModel" name="service" [(ngModel)]="operator.service">
<option *ngFor='let service of services' [ngValue]='service'>{{service.name}}</option>
</select>
<label >Enabled</label>
<label>
<input type="checkbox" name="enabled" [(ngModel)]="operator.enabled">
</label>
<button type="submit">Create Operator</button>
</form>
.ts
operator: Operator;
ngOnInit() {
this.operator = <Operator>{}; // // Initialize empty object, type assertion, with this we loose type safety
}
addOperator(isValid: boolean) {
if (isValid) {
this.operatorsService.addOperator(this.operator).then(operator => {
this.goBack();
});
}
}
Also im importing this
import { FormsModule, ReactiveFormsModule } from '#angular/forms';

Set model date defaultValue to string

I try to build a 'task manager' to log the tasks that my customers send me.
I have my new-task.hbs form
<div id="new-task-form" class="col-md-12">
<form>
<div class="form-group">
<label>Customer</label>
{{input type="text" class="form-control" value=customer placeholder="Add Customer..."}}
</div>
<div class="form-group">
<label>Task</label>
{{textarea class="form-control" value=task placeholder="Add Task..."}}
</div>
<div class="form-group">
<label>Incoming</label>
{{input type="number" class="form-control" value=incoming placeholder="Bring it on..."}}
</div>
<div class="form-group">
<label>Pending</label>
{{input type="number" class="form-control" value=pending placeholder="Don't bring it on..."}}
</div>
<div class="form-group">
<label>Closed Date</label>
{{input type="date" class="form-control" value=closed_date placeholder="Please close me..."}}
</div>
<button {{action 'addTask'}} class="btn btn-primary">Submit</button>
</form>
My controller.
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
addTask: function(){
var customer = this.get('customer');
var task = this.get('task');
var incoming = this.get('incoming');
var pending = this.get('pending');
var closed_date = this.get('closed_date');
//Create new task
var newTask = this.store.createRecord('task',{
customer: customer,
task: task,
incoming: incoming,
pending: pending,
closed_date: closed_date
});
//save to db
newTask.save();
}
}
});
And the model
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
export default Model.extend({
customer: attr('string'),
task: attr('string'),
incoming: attr('number', { defaultValue: 0 }),
pending: attr('number', { defaultValue: 0 }),
closed_date: attr('date'),
created: attr('string', {
defaultValue: function(){
return new Date();
}
})
});
How can i set a model defaultValue for a the closed_date input to a string "Not entered yet"?
If i leave it like this and not enter a value i get an "Invalid Date".
closed_date: attr('date')
If i set this i get the current date.
closed_date: attr('date', { defaultValue: 'Not entered yet' })
From my experience I suggest you leave closed_date as it is (as date) and focus on DISPLAYING Not entered yet in each place that you want to show it when closed_date isn't entered.
For example when you show model values in template you can use:
Closed date: {{if model.closed_date model.closed_date 'Not entered yet'}}
Consider using ember-pikaday for a nice date-selection experience (which also gives you the placeholder functionality you are looking for!).
Furthermore, I'd suggest that you use the model hook of your new-task route to do your model setup. Combine that with ember-data-route to do cleanup on route exit, and you should be good to go:
router.js:
this.route('tasks', function() {
this.route('new');
});
routes/tasks/new.js:
import Ember from 'ember';
import DataRoute from 'ember-data-route';
export default Route.extend(DataRoute, {
model() {
return this.store.createRecord('task');
}
});
Note below how the form field values have been updated to model.fieldName. These values are bound to the model you created in your route's model hook.
templates/tasks/new.hbs:
<div id="new-task-form" class="col-md-12">
<form>
<div class="form-group">
<label>Customer</label>
{{input type="text" class="form-control" value=model.customer placeholder="Add Customer..."}}
</div>
<div class="form-group">
<label>Task</label>
{{textarea class="form-control" value=model.task placeholder="Add Task..."}}
</div>
<div class="form-group">
<label>Incoming</label>
{{input type="number" class="form-control" value=model.incoming placeholder="Bring it on..."}}
</div>
<div class="form-group">
<label>Pending</label>
{{input type="number" class="form-control" value=model.pending placeholder="Don't bring it on..."}}
</div>
<div class="form-group">
<label>
Closed Date:
{{pikaday-input value=model.closedDate placeholder="Please close me..."}}
</label>
</div>
<button {{action 'addTask'}} class="btn btn-primary">Submit</button>
</form>
Note: prefer camelCasedMultipleWordModelAttributeName vs underscored_attribute_name
models/task.js:
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
export default Model.extend({
customer: attr('string'),
task: attr('string'),
incoming: attr('number', { defaultValue: 0 }),
pending: attr('number', { defaultValue: 0 }),
closedDate: attr('date', {
defaultValue() { return new Date(); }
}),
created: attr('string', {
defaultValue() { return new Date(); }
})
});
Now the nice part. Here's what your controller action looks like when you do your setup in your route's model hook:
controllers/tasks/new.js
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
addTask: function(){
this.get('model').save();
}
}
});
and for extra credit you could install ember-route-action-helper and move the controller action onto the route and remove the controller completely.

meteor template.dynamic load data from session

i have a page split in two:
on left {{> expenseList }}
on right {{> Template.dynamic template="expenseForm" data=expenseData}}
on left its a list
on right its a form to enter elements in the list.
desired behaviour:
1: form is empty and ready to add expenses
2: add an expense, form is cleared and ready for next
3: if i click on the left on the submitted expense from {{> expenseList }} the form is populated with the data of that expense and i can update that entry.
i cannot get it to work though. my form doesn't dynamically change the data. i tried to simplify code and add it below
the page code:
<template name="claimsPage">
<div class="wrapper wrapper-content animated fadeInRight">
<div class="row">
<div class="col-md-4">
{{> expenseList }}
</div>
{{> Template.dynamic template="expenseForm" data=expenseData}}
</div>
</div>
</template>
the page js
Template.claimsPage.helpers({
expenseData: function() {
var data = Session.get('expenseData');
return data;
}
});
the list js
Template.expenseList.events({
'click a': function(e) {
e.preventDefault();
var data = {
date: this.date,
description: this.description,
_id: this._id
};
Session.set('expenseData', data);
}
});
the form js
Template.expenseForm.helpers({
purposes: function() {
return Purposes.find();
},
expenseData: function(){
return Session.get('expenseData')
}
});
Template.expenseForm.events({
'click #add-expense': function(e){
e.preventDefault();
var template = Template.instance();
var expense = {
date: template.find("[name='date']" ).value,
description: template.find("[name='description']" ).value,
purposeName: template.find("[name='purpose'] option:selected" ).value,
_id: Random.id()
};
Meteor.call('addExpense', expense, function(error, result) {
if (error)
return alert(error.reason);
template.find("form").reset();
});
}
});
the form html
<template name="expenseForm">
<form>
<input name="date" type="text" value="">
<input name="description" type="text" value="">
<select name="purpose">
<option value="">Select a purpose</option>
{{#each purposes}}
<option value="{{this.purposeName}}">{{this.purposeName}}</option>
{{/each}}
</select>
<button id="add-expense" type="button">Submit</button>
</form>
</template>
I would really appreciate your help with this,
Thanks,
Cezar

Meteor - Data saving issue

I have this template:
<Template name="nuevoEjercicio">
<div class="container-fluid">
<div class="form-group">
<input type="text" class="form-control input-lg" name="ejercicio" placeholder="Ejercicio?"/>
<input type="number" class="form-control" name="repeticiones" placeholder="Repeticiones?" />
<input type="number" class="form-control" name="peso" placeholder="Peso?" />
<button type="submit" class="btn btn-success" >
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
</div>
</Template>
that I use to capture and save to the database.
Then on my .js file I am trying to get the data and save it:
Template.nuevoEjercicio.events({
'click .btn btn-success': function (event) {
var ejercicio = event.target.ejercicio.value;
var repeticiones = event.target.repeticiones.value;
var peso = event.target.peso.value;
ListaRutina.insert({
rutina:"1",
ejercicio:ejercicio,
repeticiones:repeticiones,
peso:peso,
});
// Clear form
event.target.ejercicio.value = "";
event.target.repeticiones.value = "";
event.target.peso.value = "";
// Prevent default form submit
return false;
}
});
}
as I understand, when I click on any object that has the btn btn-success style....but is not the case. For some obscure reason -for me- is not working.
Can you check it and give me some advice?
Thanks!
First of all, there's an error in you selector. It's 'click .btn.btn-success', not 'click .btn btn-success'.
Also you can't do that event.target.ejercicio.value thing. event.target is the element that was clicked. You'll have to do something like this:
'click .btn.btn-success': function (event, template) {
var ejercicio = template.$('[name=ejercicio]').val()
...
OK
What after wasting hours and hours the solution is:
1- on the html file give your input an id:
<input type="number" class="form-control" **id="peso"** placeholder="Peso?" />
<button type="submit" class="btn .btn-success" id="**guardar**" />
so now you want to save data on the input when the button is clicked:
2- You link the button with the funcion via the id
Template.TEMPLATENAMEONHTMLFILE.events({
'click **#guardar**': function (event, template) {
var ejercicio = template.$("**#peso**").val();
and get the value linking using the input id.