So I'm learning Node.js and Express and using it to make a simple web app that conducts CRUD operations on a mongoDB database. I can successfully insert information into the database and update it however I cannot seem to figure out how to update checkbox information. Note I looked at Passing checkbox values to database using JavaScript and it didn't help since it's in meteor.js
In my EJS file. This is the information the user has to insert in order to update a matching entry in the database. I've omitted some elements of the form for the sake of brevity.
<div id="editForm" hidden>
Enter name of the entry you want to edit?<input type="text" placeholder="full name" id="editItem" name="editItem" required><br>
Full Name<input type="text" placeholder="full name" id="fullName" name="name" required><br>
Age <input type="number" name="age" min="18" max="95" id="age" required><br>
Programming Languages <br> <input type="checkbox" class="p_languages2" name="p_languages2" value="Java" required>Java
<input type="checkbox" name="p_languages2" class="p_languages2" value="C++">C++
<input type="checkbox" name="p_languages2" class="p_languages2" value="Python">Python
<input type="checkbox" name="p_languages2" class="p_languages2" value="Ruby">Ruby
<input type="checkbox" name="p_languages2" class="Jp_languages2" value="JavaScript">JavaScript<br>
Available to start work? <input type="date" id="start_date" name="start_date" required><br>
Life Motto? <input type="text" placeholder="motto" id="motto" name="motto" required><br>
<button onClick='putRequest()' type="submit" id="editEntry">Submit</button>
</div>
function putRequest() {
fetch('/view', {
method: 'PUT',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
'editedItem': document.getElementById("editItem").value,
'name': document.getElementById("fullName").value,
'age': document.getElementById("age").value,
//how can I extract the checkboxes?
'start_date': document.getElementById("start_date").value,
'motto': document.getElementById("motto").value
})
})
window.location.reload(true);
And here's my put request for extra information. Note that "p_languages": req.body.p_languages is just a placeholder, I know it doesn't work.
app.put('/view', function(req, res) {
console.log("Put is working!");
db.collection('jobs').findAndModify(
{"name": req.body.editedItem },
{},
{$set:
{ "name": req.body.name , "job_title": req.body.job_title, "gender": req.body.gender,
"p_languages": req.body.p_languages, "age": req.body.age, "start_date": req.body.start_date,"motto": req.body.motto }
},
{},
function(err, object) {
if (err){
console.warn(err.message); // returns error if no matching object found
}else{
console.log("Update complete");
}
})
})
You can refer to all checkboxes by name attribute like this,
var checkboxes = document.getElementsByName("p_languages2");. This will return array checkboxes with p_languages2. Now you just need to iterate over this array and get the value of all the checkboxes which are checked checkboxes[i].checked and store that values in an array and update that array on server. Refer to this plnkr.
Related
I am using this form to take some basic information:
<form action="/action_page.php" method="GET" name="clientForm">
<label for="cname">Client name:</label><br>
<input type="text" id="cname" placeholder="client name:" name="cname" required><br>
<label for="clienturl">URL:</label><br>
<input type="text" id="clienturl" placeholder="url:" name="clienturl" required><br><br>
<input type="submit" value="Submit" button (click)="addClient()" >
<input type="reset" value="Reset">
</form>
This is the data i am currently holding:
export const clients = [
{
name: 'client1',
url: "https://www.google.com"
},
{
name: 'client2',
url: "https://www.yahoo.com"
},
{
name: 'ACB',
url: "https://www.dailymail.co.uk"
},
{
name: 'client3',
url: "https://www.youtube.com"
},
{
name: 'client4',
url: "https://www.nhs.uk"
},
];
Then in my component I am struggling to get the data entered into the form and add it as an object to the existing data.
If you use the Reactive Forms / Angular Standard Forms in your angular app, you can get it...
<form [formGroup]="FormName" (ngSubmit)="submit()">
in TypeScript:
this.FormName.value
For more details, see the official documents
By using the traditional way, you can add in to the object
This is a noob question. What I'd like to do is set up a birthday party reservation website that has people fill out a form: yes/ no will attend, name, email. After the form is filled out for 'will attend' I'd like to have a popup modal that has the option to 'add to your calendar: Google, iCal, etc.'
Is this possible in an html form (javascript/ ajax)? I know it can be done in WordPress.
Thank you for any help/ suggestions.
Here is a very basic idea of what you could do. I put the form in the console using the answer here: https://stackoverflow.com/a/47188324/12946266 you will need to use php to operate on this form most likely, but I can't use that here.
const form = document.querySelector('form');
document.getElementById("myForm").addEventListener("submit", function(event) {
event.preventDefault();
var values = Object.values(form).reduce((obj, field) => {
if(field.type=='radio'){
obj[field.name] = field.checked;
}else{
obj[field.name] = field.value;
}
return obj
}, {})
console.log(values);
});
<form id="myForm" action="/action_page.php">
First name: <input type="text" name="fname" value=""><br> Last name: <input type="text" name="lname" value=""><br> email: <input type="text" name="email" value=""><br>
<input type="radio" id="attending" name="attendance" value="attending">
<label for="attending">attending</label>
<br>
<input type="submit" value="Submit"><br>
</form>
This is the HTML that i created for the registration page
<form role="form" action="" method="post" id="register_form">
<input type="text" id="facebook-autocomplete" name="facebook" class="form-control mdb-autocomplete GJ-search">
<input type="text" id="beatport-autocomplete" name="beatport" class="form-control mdb-autocomplete GJ-search" required>
<input type="email" id="inputValidationEmail" name="email" class="form-control" >
<input type="password" id="inputValidationPass" name="password" class="form-control" >
<input type="checkbox" class="custom-control-input" name="termsAndConditions" id="termsAndConditions" >
<input type="checkbox" class="custom-control-input" name="gdprAccept" id="gdpr" >
<button class="btn btn-outline-info btn-rounded btn-block my-4 waves-effect z-depth-0" value="Submit" type="submit">Sign up</button>
</form>
This is the JavaScript that extracts the form to JSON and console logging it and it works.
//stringify form to JSON string
const serialize_form = form => JSON.stringify(
Array.from(new FormData(form).entries())
.reduce((m, [ key, value ]) => Object.assign(m, { [key]: value }), {})
);
$('#register_form').on('submit', function(event) {
event.preventDefault();
const json = serialize_form(this);
console.log(json);
});
I add two new attributes to the beatport input by adding this jquery
$('.beatport #beatport-autocomplete').attr('data-beatport-id', "id pulled from api");
$('.beatport #beatport-autocomplete').attr('data-beatport-name', "name pulled from api");
The Json Result is after adding two new attributes is:
{"facebook":"big show","email":"dfghdfsghg#gmail.com","password":"fsdghfjgh","termsAndConditions":"on","gdprAccept":"on"}
You see that the two new attr are missing and when I add them the input looks like this:
<input type="text" id="beatport-autocomplete" name="beatport" class="form-control mdb-autocomplete GJ-search" required data-beatport-id="12345" data-beatport-name="artist name">
and the JSON result should be like this:
{"facebook":"big show","beatportId":"12345","beatportName":"artist name","email":"dfghdfsghg#gmail.com","password":"fsdghfjgh","termsAndConditions":"on","gdprAccept":"on"}
If you want to add data to your form you can use hidden input and set the value via js
HTML
<input type="hidden" name="beatportID">
JS
$('[name="beatportID"]').attr('value', 'my data');
If you are looking to extract data attributes from a html element and you are using jQuery already to set them i think the following might be what you are looking for. (Not exactly sure from your question what your desired result is) if possible perhaps you could explain a little further?
https://api.jquery.com/data/
Please check below for an example of that i mean.
Firstly lets say the following is your registration form.
<input type="text" id="name" />
<input type="text" id="email" />
<input type="text" id="phone" />
<input type="text" id="age" />
You would then add your two data attributes to let say the name input.
$('#name').attr('data-beatport-id', "id pulled from api");
$('#name').attr('data-beatport-name', "name pulled from api");
You can then serialize_form and add it to json variable.
let json = serialize_form(this);
And then use the following to get data attributes from the '#name' input.
json.beatport-name = $('#name').data("beatport-name")
json.beatport-id = $('#name').data("beatport-id")
You can then console log this json object.
console.log(json)
I've been searching the internet for a long time now and I've yet not managed to find any useful information on this problem.
Use case:
POST Data to mongo database using EJS and Mongoose.
This is a simple registration for users in a Modal View.
This is my Registration Form:
Top.ejs
<form id="register-form" action="/" method="POST" style="display:none" enctype="multipart/form-data">
<div class="modal-body">
<div id="div-register-msg">
<div id="icon-register-msg" class="glyphicon glyphicon-chevron-right"></div>
<span id="text-register-msg">Register</span>
</div>
<input name="firstname" class="form-control" type="text" placeholder="Firstname" required>
<input name="lastname" class="form-control" type="text" placeholder="Lastname" required>
<input name="email" class="form-control" type="email" placeholder="Email" required>
<input name="phonenumber" class="form-control" type="number" placeholder="Phonenumber" required>
<input name="password" class="form-control" type="password" placeholder="Password" required>
<input name="password_c" class="form-control" type="password" placeholder="Confirm" required>
</div>
<div class="modal-footer">
<!--<div class"checkbox">
<label><input type="checkbox">I have read and understood the terms for Debate.It</label>
</div>-->
<input type="submit" class="btn btn-success btn-block" value="Register">
</div>
</form>
Below you'll see the POST Route. Please be aware that this is working with POSTMAN. The data is posted into a mongoLab online database. Working like a charm.
router.post('/', jsonParser, function (req, res){
mongoose.connect(url, function(err, db) {
console.log(req.body);
console.log("User created!");
var user = {
firstname : req.body.firstname,
lastname : req.body.lastname,
email : req.body.email,
phonenumber : req.body.phonenumber,
password : req.body.password
};
UserReq.create(user, function(err, data) {
if(err) {
res.status(400);
}
else {
res.status(201);
//res.send(data);
res.json(data);
mongoose.disconnect();
}
});
});
});
I do not believe there is anything particular wrong with the route, but might be the EJS Page.
Here you'll see my Modal View. The Form's are in a single file, but they have been separated into their own forms and given an ID.
Alright, so when I click the "Register"-button I do not get any action at all. I've tried with some JQuery, but I don't get any action.
I hope anyone in here can help me out. Maybe give me a tip and some theory behind.
If you've any misunderstandings in my explaining, please do hesitate to tell me. I will correct it or try to be more clear. This is written just 5 minutes before the guests for Christmas arrives.
Have a wonderful Christmas everyone. May you all have a wonderful night.
Is there any way to save HTML Form schema to JSON?
E.g. when I have something like this
<form>
First name:<br>
<input type="text" name="firstname">
<br>
Last name:<br>
<input type="text" name="lastname">
</form>
How i can achieve somehting like this:
[
{
field: 'input',
type: 'text',
name: 'firstname'
},
{
field: 'input',
type: 'text',
name: 'lastname'
},
]
I dont mean that it has to be exact output as above, but how I can achieve something similar?
The idea is to do something like this. You can iterate through form elements collection of elements, and use every element to extract necessary information.
In code below I used Array.prototype.map method, but maybe it would be more convenient to go with simple for loop. It would give you more room for customization.
function serializeSchema(form) {
return [].map.call(form.elements, function(el) {
return {
type: el.type,
name: el.name,
value: el.value
};
});
};
var form = document.querySelector('form'),
schema = serializeSchema(form);
alert(JSON.stringify(schema, null, 4));
<form>
<input type="text" name="firstname" value="Test">
<input type="text" name="lastname">
<select name="age" id="">
<option value="123" selected>123</option>
</select>
<input type="checkbox" name ="agree" value="1" checked> agree
</form>
Also one more note. What you are trying to achieve is very similar to what jQuery's $.fn.serializeArray method does (it doesn't collect type). However it's pretty simple to extend serializeArray to make it also return type of the elements.