I'm trying to figure out how to pass in the event object so that I can have event.preventDefault if no checkboxes are selected and show an alert on the page.
HTML
<form>
<div style="display: flex; justify-content: center">
<label><b>Environments:</b></label>
<label>
<input
type="checkbox"
th:text="QA"
th:field=*{qa}
/>
<label>
<label>
<input
type="checkbox"
th:text="Stage"
th:field=*{Stage}
/>
<label>
</div>
<button type="submit" th:id="submitSecret" th:onclick="validateEnv()>Submit</button>
</form>
JS
const validateEnv = () => {
let qa = document.getElementById("qa").checked;
let stage = document.getElementById("stage").checked;
if (!qa && !stage) {
// event.preventDefault()
alert('Please select an environment')
}
}
Related
Hello i want asking about pushing array from form
This is sample my code post form to id
how to turn bellow form from post to id, to push to array.
function handleName(e) {
setInputForm({ ...inputForm, nama: e.target.value });
}
function handleJam(e) {
setInputForm({ ...inputForm, jam: e.target.value });
}
{formMode !== "" && (
<div id="form" className="card py-2 my-3 bg-secondary">
<div className="card-body">
<h4>Add </h4>
<form className="row" onSubmit={submitForm}>
<div className="col-5">
<input
type="text"
name="nama"
className="form-control mx-2"
placeholder="nama..."
value={inputForm.nama || ""}
onChange={handleName}
/>
</div>
<div className="col-2">
<input
type="text"
name="jam"
className="form-control mx-2"
placeholder="Jam ..."
value={inputForm.jam || ""}
onChange={handleJam}
/>
</div>
<div className="col-2">
<input
type="submit"
className="btn btn-success"
value="Send"
/>
</div>
</form>
</div>
</div>
)}
i can use push on postman with this way
put -> localhost:4000/kelas/update/:id
{
"$push":{
"jadwal":
[
{
"nama":"Susanti",
"jam":"12"
}
]
}
}
I am new in node js and trying to integrate single file upload using dropzone js. I want to upload image before submitting form. I have managed to call the upload action before submitting.
Here is my html code:
<form id="add_user" name="add_user" class="form-horizontal" action="/add-new-user" method="POST">
<div class="directory-bg text-center">
<div class="directory-overlay">
<span id="imageuploader">
<input name="profileimg" id="profileimg" type="hidden" value="">
<img id="ws_user_avatar" class="rounded-circle thumb-lg img-thumbnail dropzone" data-thumb="public/assets/images/users/user.png" src="public/assets/images/users/user.png" alt="Generic placeholder image">
<!--<div class="fallback">
<input name="image" id="image" type="file">
</div>-->
x
</span>
</div>
</div>
<div class="directory-content p-4">
<div class="mt-4">
<% if(success != "") {%>
<div class="alert alert-success" role="alert">
<strong>Done!</strong> <%= success %>
</div>
<% } %>
<div class="row">
<div class="col-md-12">
<div class="mb-3">
<label class="form-label" for="email">Email Address</label>
<input type="email" class="form-control" name="email" id="email" placeholder="Email Address" data-key="Email Address" autocomplete="off" autofill="false">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="mb-3">
<label class="form-label" for="fname">First Name</label>
<input type="text" class="form-control" name="fname" id="fname" placeholder="First Name" data-key="First Name" autocomplete="off" autofill="false">
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label class="form-label" for="lname">Last Name</label>
<input type="text" class="form-control" id="lname" name="lname" placeholder="Last Name" data-key="Last Name" autocomplete="off" autofill="false">
</div>
</div>
</div>
</div>
</div>
</form>
Here is the js code to handle dropzone event
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone(".dropzone", {
url: '/upload-image',
autoProcessQueue: false,
uploadMultiple: false,
maxFiles:2,
maxFilesize: 2,
createImageThumbnails:false,
hiddenInputContainer: "img.rounded-circle",
init: function(file) {
var prevFile = null;
this.on("addedfile", function(file) {
var $this = this;
setTimeout(function () {
if(file.status == "error"){
alert(file.previewTemplate.innerText);
} else {
if(prevFile){
$this.removeFile($this.files[0])
}
prevFile = file;
$("#user_avatar").attr('data-imgname', file.name);
previewImage($this);
}
}, 10);
});
}
});
function previewImage(input){
let fileReference = input.files && input.files[0];
if(fileReference){
var reader = new FileReader();
reader.onload = (event) => {
document.getElementById('user_avatar').src = event.target.result;
}
reader.readAsDataURL(fileReference);
}
}
$(document).on('click','#btn_submit', function(e){
e.preventDefault();
if(myDropzone.getQueuedFiles().length > 0){
myDropzone.processQueue();
} else {
$("#add_user").submit();
}
});
Here is the post handler code in router.js file:
const express = require('express');
const router = express.Router();
router.post('/upload-image', function(req, res){
console.log('requested inage',req.files.file.path);
// fs.readFile(request.files.file.path, function(err, data) {
// var newPath = __dirname + "/public/img/xspectra/customlogo.png";
// fs.writeFile(newPath, data, function (err) {
// console.log("Finished writing file..." + err);
// response.redirect("back");
// });
// });
});
When the dropzone myDropzone.processQueue() function called, I get an error message in the post handler function TypeError: Cannot read property 'file' of undefined.
Can anyone suggest me where I am doing wrong?
Many Thanks!
That means that the file uploaded didn't properly make it to your web server. Are you using express-fileupload on the nodejs side to handle the uploads?
If so, I recommend checking out this link on a really great tutorial
I broke my form and am trying to make two different pages and finally PUT data to same initial route(ACTION), but I see data from the second page
only:
This is the first part of the form which I broke into the first page, keeping the action same:
<div class="container">
<div class="row">
<h1 style="text-align: center">Register Yourself</h1>
<div style="width: 30%; margin: 25px auto;">
<form action="/students" method="POST">
<label>Name:</label> <div class="form-group">
<input class="form-control" type="text" name="name" placeholder="name">
</div>
</form>
Proceed!
</div>
</div>
</div>
This is the second part of the form which I put in the second page:
<div class="container">
<div class="row">
<h1 style="text-align: center">Register Yourself</h1>
<div style="width: 30%; margin: 25px auto;">
<form action="/students" method="POST">
<label for="preference">Choose a catagory:</label>
<select name="preference" class="form-control">
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Any">Any</option>
</select>
</div>
<div class="form-group">
<button class="btn btn-sm btn-primary ">Submit!</button>
</div>
</form>
</div>
</div>
</div>
This is the route where we are taking data from form and adding to the db and posting finally:
router.post("/students",middleware.isLoggedIn, function(req, res){
// get data from form and add to students array
var name = req.body.name;
var preference = req.body.preference;
var author = {
id: req.user._id,
username: req.user.username
}
var newstudent = {name: name,preference: preference}
// Create a new student and save to DB
Student.create(newstudent, function(err, newlyCreated){
if(err){
console.log(err);
} else {
//redirect back to students page
console.log(newlyCreated);
res.redirect("/students");
}
});
});
I think you can follow this approach, however, if you have really big form. I advise you to create Modals for every step. Also, recommend you to create separate controller for forms. This is how you can achieve for the above form:
// I am assuming that you will show first form and then second form as there is no validation added
var formData = {name: name,preference: preference}; // when you have big forms create model for it
//step will make your route dynamic
router.post("/students/:step",middleware.isLoggedIn, function(req, res){
// get data from form and add to students array
if (req.params.step == 1) {
formData.name = req.body.name;
return '' //do nothing as you should submit form in next step
}
else {
formData.preference = req.body.preference;
Student.create(formData, function(err, newlyCreated){
if(err){
console.log(err);
} else {
//redirect back to students page
console.log(newlyCreated);
// res.redirect("/students"); // you don't need to redirect
formData = {name:'' ,preference: ''};
res.status(201).send({message: 'New User Created'});
}
});
}
});
In your HTML code:
<div class="container">
<div class="row">
<h1 style="text-align: center">Register Yourself</h1>
<div style="width: 30%; margin: 25px auto;">
<form action="/students/1" method="POST"> //add id for every step
<label for="preference">Choose a catagory:</label>
<select name="preference" class="form-control">
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Any">Any</option>
</select>
</div>
<div class="form-group">
<button class="btn btn-sm btn-primary ">Submit!</button>
</div>
</form>
</div>
</div>
</div>
<div class="container">
<div class="row">
<h1 style="text-align: center">Register Yourself</h1>
<div style="width: 30%; margin: 25px auto;">
<form action="/students/2" method="POST"> //add id for every step
<label for="preference">Choose a catagory:</label>
<select name="preference" class="form-control">
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Any">Any</option>
</select>
</div>
<div class="form-group">
<button class="btn btn-sm btn-primary ">Submit!</button>
</div>
</form>
</div>
</div>
</div>
At this moment, I can think of this approach.
I am trying to edit the record but I get the same result on clicking the edit button. Result of selected is not coming instead the first one is coming every time. I want to fetch the detail on clicking the edit button.
Getting result
If I click edit button of anyone it gets same value as above picture
router.js
router.get('/editCategory/:id', async (req,res,next) => {
const { id } = req.params;
const categories = await Category.findById({_id: id });
res.render('category', {
categories
});
res.json(data);
});
router.post('/editCategory/:id', async (req,res,next) => {
const { id } = req.params;
console.log(req.body);
const ctgy = await Category.findOne(id);
Object.assign(record, req.body);
await ctgy.save();
res.redirect('/category');
});
category.ejs
<tbody>
<% for(var i = 0; i <categories. length; i++) { %>
<tr>
<td><%= i+1 %></td>
<td><%= categories[i].category %></td>
<td><%= categories[i].status %></td>
<td>
<!-- Button trigger modal -->
<button type="button" class="btn bg-blue-w rounded edit" data-toggle="modal" data-target="#changecategoryModal">Edit</button>
<!-- Modal -->
<div class="modal fade" id="changecategoryModal" tabindex="-1" role="dialog" aria-labelledby="changecategoryModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="changecategoryModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="/edit/<%= categories[i]._id %>" method="post" enctype="multipart/form-data" id="categoryform">
<div class="form-group">
<label class="label-text">change Category</label>
<input type="text" class="form-control" placeholder="Category" name="category" value="<%= categories[i].category %>">
</div>
<div class="form-group">
<label class="label-text">Change image</label>
<input type="text" class="form-control" placeholder="Category" name="category" value="<%= categories[i].status %>">
<!-- <input type="file" name="myimage" value=""> -->
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<input type="submit" value="submit" class="btn bg-red rounded" form="categoryform">
</div>
</div>
</div>
</div>
</div>
Delete
</td>
</tr>
<% } %>
</tbody>
Error is in the below Line
const { id } = req.params;
when you are trying to destructor the req.params object , the value of id is not set. That is why query is returning the first row document every time.
Try to log the value of id and check.
in the second route
const ctgy = await Category.findOne(id);
the findOne accepts the object eg: Category.findOne({_id:id})
I want to take the input from the user and check the value of it whether it matches the value exists in firebase database or not.
I want to build a login component which provides the functionality of signUp user and signIn. I know it can be implemented by Auth but I want to use custom data. I was able to perform CRUD operations.enter image description here
This is login.component.ts where I want to implement the function
export class LoginComponent implements OnInit {
adminval: string;
passwordval : string;
newnew : string = 'employeeService.loginData.admin';
loginList : LoginID[];
constructor(private employeeService : EmployeeService, private router : Router) { }
ngOnInit() {
this.employeeService.getLoginData();
var x = this.employeeService.getLoginData();
x.snapshotChanges().subscribe(item =>{
this.loginList = [];
item.forEach(element => {
var y = element.payload.toJSON();
y["$key"] = element.key;
this.loginList.push(y as LoginID);
})
})
}
onEdit(emp : LoginID){
this.employeeService.loginData = Object.assign({}, emp);
}
onLogin(loginForm : NgForm){
if(this.adminval == this.employeeService.loginData.admin){
alert("OK");
}
else
alert("Not OK");
}
}
Here the login.component.html file code
<body style="background-color:#DD3247">
<div class="container" style="padding-top: 10%; padding-bottom: 8.1%;">
<div class="row justify-content-md-center">
<div class="col-md-5 login-box">
<h1 class="text-center login-text-color">Login</h1>
<hr>
<form #loginForm="ngForm">
<input type="hidden" name="$key" #$key="ngModel" [(ngModel)]="employeeService.loginData.$key">
<input type="hidden" name="admin" #admin="ngModel" [(ngModel)]="employeeService.loginData.admin" placeholder="Admin">
<input type="hidden" name="password" #password="ngModel" [(ngModel)]="employeeService.loginData.password" placeholder="Password">
<div class="form-row">
<div class="col-md-12">
<input type="text" class="form-control form-control-lg flat-input" name="adminvalue" #adminvalue="ngModel" [(ngModel)]="adminval" placeholder="Admin" required>
</div>
<div class="col-md-12">
<input type="password" class="form-control form-control-lg flat-input" name="passwordvalue" #passwordvalue="ngModel" [ngModel]="passwordval" placeholder="Password" required>
</div>
<button type="submit" class="btn btn-lg btn-block btn-login" (click)="onLogin(loginForm)">Login</button>
</div>
</form>
</div>
</div>
</div>
<div class="container">
<div class="row justify-content-md-center">
<h6 class="text-center">Employee Register</h6><br>
<table class="table table-sm table-hover">
<tr *ngFor="let login of loginList">
<td>{{login.admin}}</td>
<td>{{login.password}}</td>
<td>
<a class="btn" (click)="onEdit(login)">
<i class="fa fa-pencil-square-o"></i>
</a>
<a class="btn">
<i class="fa fa-trash-o"></i>
</a>
</td>
</tr>
</table>
</div>
</div>
</body>
Somehow, I was able to do it by matching username value but by the wrong implementation. You can see there are 3 input hidden fields in the HTML file so first I have to click on the edit icon then that will insert the existing data into the hidden fields and then if the input from the adminval matches the one of the admin hidden field then it will show OK otherwise Not Ok.