How to bind & save radio button values in angular 2? - node.js

Here I'm using the nested property Schema of mongoose to nest all the "stages" then using formGroup in typescript.
I'm not sure what should be the formControlName for the radio
buttons as it needs to be similar?
Also, not sure if I'm missing anything?
Code:
// Schema
const userSchema = new Schema({
name: { type: String, required: true },
email: { type: String, required: true },
stages: {
stageOne: { type: Boolean, default: false },
stageTwo: { type: Boolean, default: false },
stageThree: { type: Boolean, default: false }
});
// typescript/component.ts
this.form = this.formBuilder.group({
name: [''],
email: [''],
stages: this.formBuilder.group({
stageOne: [null],
stageTwo: [null],
stageThree: [null]
});
});
// html/template.html
<form [formGroup]="form">
<div class="form-group">
<input name="name" class="form-control" id="name" type="text" [(ngModel)]="name" formControlName="name">
<input name="email" class="form-control" id="email" type="email" [(ngModel)]="email" formControlName="email">
<div class="custom-control custom-radio">
<input type="radio" id="stageOne" class="custom-control-input" [(ngModel)]="stageOne" formControlName="???">
<label class="custom-control-label" for="stageOne">1</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" id="stageTwo" class="custom-control-input" [(ngModel)]="stageTwo" formControlName="???">
<label class="custom-control-label" for="stageTwo">2</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" id="stageThree" class="custom-control-input" [(ngModel)]="stageThree" formControlName="???">
<label class="custom-control-label" for="stageThree">3</label>
</div>
</div>
</form>

It is no different than with your other input form controls. However, the ControlValueAccessor will get the value from your radio button so you do not require the additional ngModel directives. When you submit your form the from object itself, this.form.value, will contain all your form values.
Reactive Form
this.form = this.formBuilder.group({
name: [''],
email: [''],
stages: ['1']
});
Template
<form [formGroup]="form">
<div class="form-group">
<input name="name" class="form-control" id="name" type="text" formControlName="name">
<input name="email" class="form-control" id="email" type="email" formControlName="email">
<div class="custom-control custom-radio">
<input type="radio" id="stageOne" class="custom-control-input" formControlName="stages" [value]="1">
<label class="custom-control-label" for="stageOne">1</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" id="stageTwo" class="custom-control-input" formControlName="stages" [value]="2">
<label class="custom-control-label" for="stageTwo">2</label>
</div>
<div class="custom-control custom-radio">
<input type="radio" id="stageThree" class="custom-control-input" formControlName="stages" [value]="3">
<label class="custom-control-label" for="stageThree">3</label>
</div>
</div>
</form>

Related

setting up default images on a restful routes create route

I am relatively new to coding and have been working on a restful routes exercise for an online course using a MEN stack. In the exercise, I am trying to use a default image when no data is entered into the /new route form. I have already indicated a default image in my mongoose schema, but it doesn't seem to be working when I leave the image field blank on my form. It creates a new post with a "unknown" src attribute. I have attached code for my schema, my /new ejs form, and new and create routes. Thanks for any help!
(MONGOOSE SCHEMA)
var catSchema = new mongoose.Schema({
name : String,
description: String,
ranking: Number,
image: {type: String, default: "https://i.cubeupload.com/SnsWs2.png"},
created: {type:Date, default: Date.now}
(NEW AND CREATE ROUTES)
app.post("/cats", function(req,res){
Cat.create(req.body.cat, function(err,newBlog){
if(err){
res.redirect("/cats/new")
}else{
res.redirect("/cats")
}
});
});
(NEW ROUTE)
<%- include("partials/header") %>
<div class="container">
<form action="/cats" method="POST">
<div class="form-group">
<label required for="cat[name]">Name</label>
<input type="text" name="cat[name]" class="form-control" id="name" aria-describedby="emailHelp" placeholder="Enter cat name">
</div>
<div class="form-group">
<label for="cat[description]">Description</label>
<input type="text" class="form-control" name="cat[description]" placeholder="description">
</div>
<div class="form-group">
<label for="cat[ranking]">Ranking</label>
<input type="number" class="form-control" name="cat[ranking]" placeholder="Password">
</div>
<div class="form-group">
<label for="cat[image]">Ranking</label>
<input type="text" class="form-control" name="cat[image]" placeholder="image URL">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>

Store form value in an array of strings in nodejs

So I have a post method in my nodejs application and I want to send a form from my ejs file to an array in one of my models. In the ejs file, I have a select option for the user to enter a list of subjects. Once submitted, I cannot get the values from the select option. I tried to store it in an array but it shows undefined. I have an instructor model where it stores the subjects fields in a list of string array. I am not sure what to do. Here is what I have:
admin.js
router.get('/newInstructor', isLoggedIn, function(req, res) {
res.render('newInstructor.ejs');
});
router.post('/newInstructor', isLoggedIn, function(req, res) {
var lisOfSubjects = [req.body.listOfSubjects];
console.log('Subjects -> ' + lisOfSubjects);
var newInstructor = new Instructor ({
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
officeNumber: req.body.officeNum,
cellNumber: req.body.cellNum,
address: {
address1: req.body.address,
address2: req.body.address2,
city: req.body.city,
state: req.body.state,
zipCode: req.body.zip
},
subjects: lisOfSubjects,
officeLocation: req.body.officeLocation
});
console.log(newInstructor);
});
ejs view file
<!-- js function to insert and remove from the select option-->
<script>
function insertTeachingSelect() {
var text = document.getElementById("subject").value;
console.log(text);
var select = document.getElementById("listOfSubjects");
select.options[select.options.length] = new Option(text, 'Value1');
}
function removeTeachingSelect() {
var removeSelect = document.getElementById("listOfSubjects");
removeSelect.remove(removeSelect.selectedIndex);
}
</script>
......
<div class="form-group">
<div class="form-row">
<div class="col-md-4">
<div class="form-label-group">
<input type="text" id="subject" name="subject" class="form-control">
<label for="Enter subject">Enter subject</label>
</div>
</div>
<div class="col-md-2">
<div class="form-label-group">
<input type="button" onclick="insertTeachingSelect()" class="btn btn-primary btn-block" value="Add more">
<input type="button" onclick="removeTeachingSelect()" class="btn btn-primary btn-block" value="Remove">
</div>
</div>
<div class="col-md-6">
<div class="form-label-group">
<input type="text" id="officeLocation" name="officeLocation" class="form-control" placeholder="Office location" required="required">
<label for="officeLocation">Office location</label>
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="form-row">
<div class="col-md-4">
<div class="form-label-group">
<select id="listOfSubjects" name="listOfSubjects"size="5"></select>
</div>
</div>
</div>
</div>
<div class="form-group ">
<div class="form-row">
<div class="col-md-6 mx-auto">
<div class="form-label-group">
<button type="submit" class="btn btn-primary btn-block">Submit</button>

Cannot POST Form in Node

I am trying to post a simple form from a static page to a database and then re-render the page. Right now I am getting a "Cannot Post /Index" error.
Here is my the form code:
<div class="contact-form">
<form action="/index" method="post">
<div class="col-md-6">
<input type="text" class="form-control" placeholder="Name" name="name">
</div>
<div class="col-md-6">
<input type="email" class="form-control" placeholder="Email" name="email">
</div>
<div class="col-md-6">
<input type="tel" class="form-control" placeholder="Phone Number" name="phone">
</div>
<div class="col-md-6">
<input type="text" class="form-control" placeholder="# of Trucks" name="truckNum">
</div>
<div class="col-md-12">
<input type="text" class="form-control" placeholder="Company" name="company">
</div>
<div class="col-md-12">
<input type="text" class="form-control" placeholder="Address" name="address">
</div>
<div class="col-md-12">
<textarea class="form-control" placeholder="Message" rows="4" name="message"></textarea>
</div>
<div class="col-md-8">
<input type="submit" class="form-control text-uppercase" value="Send">
</div>
</form>
</div>
Here is the router code:
app.get("/", function(req, res) {
res.sendFile(path.join(__dirname, "/../public/index.html"));
});
app.post("/", function(req,res){
db.Contact.create({
name: req.body.name,
email: req.body.email,
phone: req.body.phone,
company:req.body.company,
address:req.body.address,
truckNumber:req.body.truckNum
}).then(function(data) {
res.sendFile(path.join(__dirname, "/../public/index.html"));
});
})
};
Change '/index' to '/' in<form action="/index" method="post">.

Target an array in a mongo/mongoose schema using a handlebars form

.I know I am not targeting correctly my schema because I get an empty array. I want to push my input values in the staff array. It seems like there's limited handlebars documentation on input fields templating. Thanks!
My Schema:
var docketSchema = new Schema({
companyName: string,
address: string,
staff: [{ manager: String,
receptionist: String
}]
});
My handlebars template:
<div class="form-group">
<input type="text" id="address" name="address" required value="{{input.address}}">
</div>
<div class="form-group">
<input type="text" id="companyName" name="companyName" required value="{{input.companyName}}">
</div>
<div class="form-group">
<input type="text" id="manager" name="manager" required value="{{input.staff.manager}}">
</div>
<div class="form-group">
<input type="text" id="receptionist" name="receptionist" required value="{{input.staff.receptionist}}">
</div>
My route:
router.post('/create', function(req, res, next) {
userService.addDocket(req.body, function(err) {
var vm = {
input: req.body
};
res.redirect('/dockets');
});
});
My console:
[ { companyName: 'Acme',
address: 'New York',
staff: [] } ]
My addDocket method:
exports.addDocket = function(docket, next) {
var newDocket = new Docket({
companyName: docket.companyName,
address: docket.address,
staff: docket.staff
});
newDocket.save(function(err) {
next(null);
});
};
In your handlebars template, try creating the form elements with arrays as follows:
<div class="form-group">
<input type="text" id="address" name="address" required value="{{input.address}}">
</div>
<div class="form-group">
<input type="text" id="companyName" name="companyName" required value="{{input.companyName}}">
</div>
<div class="form-group">
<input type="text" id="manager" name="staff[manager]" required value="{{input.staff.manager}}">
</div>
<div class="form-group">
<input type="text" id="receptionist" name="staff[receptionist]" required value="{{input.staff.receptionist}}">
</div>

Forms not working (using Bootstrap,Node.js and mongoose)

I have this simple form code which works perfectly with the node.js and mongoose, it saves data and everything but as soon as I add my other bootstraps features it doesn't save any data into database any more. Here are the two codes:
The one which works perfectly:
<div class="row">
<div class="col-lg-12">
<div class="col-xs-8 col-sm-8 col-md-8">
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-body">
<form method="POST" action="/samples">
<input type="text" name="fullName" id="fullName" class="input-lg " placeholder="your full name" data-required="true">
<input type="text" name="age" id="age" class="input-lg" placeholder="age">
<input type="text" name="city" id="city" class="input-lg" placeholder="Your City">
<input type="text" name="job" class="input-lg" placeholder="Your Job">
<input type="text" name="username" class="input-lg " placeholder="prefered username" data-required="true">
<input type="password" name="password" class="input-lg" placeholder="Password">
<input type="email" name="email" class="input-lg " placeholder="your email" data-required="true">
<button type="submit" class="btn btn-primary">Sign in</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
and here is the one with that small addition which doesn't work:
<div class="slide story" id="slide-2" name="slide2" data-slide="2">
<div class="container">
<div class="row title-row">
<div class="col-12 font-title">"Start Exploring Here"</div>
</div>
<br><br>
<div class="row">
<div class="col-lg-12">
<div class="col-xs-8 col-sm-8 col-md-8">
<div class="container">
<div class="row">
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-body">
<form method="POST" action="/samples">
<input type="text" name="fullName" id="fullName" class="input-lg " placeholder="your full name" data-required="true">
<input type="text" name="age" id="age" class="input-lg" placeholder="age">
<input type="text" name="city" id="city" class="input-lg" placeholder="Your City">
<input type="text" name="job" class="input-lg" placeholder="Your Job">
<input type="text" name="username" class="input-lg " placeholder="prefered username" data-required="true">
<input type="password" name="password" class="input-lg" placeholder="Password">
<input type="email" name="email" class="input-lg " placeholder="your email" data-required="true">
<button type="submit" class="btn btn-primary">Sign in</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
and here is the bit of code for node.js
mongoose.connect('mongodb://localhost/Try');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
var Schema = new mongoose.Schema({
fullName:String,
age: String,
city: String,
job: String,
username: String,
password: String,
_id: String
});
var user = mongoose.model('Users',Schema);
app.post('/samples', function(req,res){
new user({
_id:req.body.email,
fullName:req.body.fullName,
age:req.body.age,
city:req.body.city,
job:req.body.job,
username:req.body.username,
password:req.body.password,
}).save(function(err, doc){
if(err) res.json(err);
else res.render('samples');
});
});
});
I can't figure out why it doesn't work. I would really appreciate it if you let me know what is the problem with that small bit which mess the whole thing.
Thanks
The slider is likely preventing the default action of your form. Try adding an explicit click listener on your button with jQuery:
$('button').click( function() {
$('form').submit();
});

Resources