Save HTML form schema to JSON - javascript

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.

Related

Send date from html form to Google calendar, etc

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>

Updating MongoDB with checkbox information

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.

AngularJS, multiple generated forms on page. How to get contents of forms

I have a web page that generates forms to updates things over REST API on remote server. The forms are generated with PHP.
The forms are as follows:
Textfield: name
textfield: description
select: type (ng-model="selection")
option a
option b
option c
textfields f1, f2, f3: some of these are hidden depending on the selection.
button that fires (update()) AngularJS when pressed.
There are multiple of such forms on the page.
How do I get the contents of the fields to pass to update() using AngularJS? I thought that I could use Javascript getElementById and do some magic to that stuff but I bet there would be a more beautiful way to do it.
In AngularJS you can bind data to your form using the ng-model property.
Check out the example from the documentation:
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<input type="button" ng-click="reset()" value="Reset" />
<input type="submit" ng-click="update(user)" value="Save" />
</form>
http://plnkr.co/edit/qr1HdCqgr7jvf5aR0Gb2?p=preview
It is a good practice to have models being part of one object and only define properties on this object (in the form above, the model for your form data is the user object and each field is used to specify a property of this object, user.email for example).
Then, in your controller, you can access your form values through the corresponding scope variable ($scope.user in our example).
You can set ng-model to each of the form fields. Inside update method you can access them using $scope object.
E.g
<input type="text" ng-model="form1.name">
<input type="text" ng-model="form1.description">
...
...
<input type="text" ng-model="form2.name">
<input type="text" ng-model="form2.description">
Js
In the update method you can access it using $scope.form1.name, $scope.form1.description
You can create tabs where every tab will be one form (editing one item), clicking on one tab it will open you the current element and you can edit it. This way you do not need to know how many elements there will be.
<div ng-app>
<article ng-controller="AplicationCtrl">
<ul>
<li ng-repeat="item in items">
Tabs {{$index}}
</li>
</ul>
<br/>
<div>
<input ng-model="selectedItem.name"/>
<input ng-model="selectedItem.description"/>
</div>
Update values
</article>
</div>
function AplicationCtrl($scope) {
$scope.items = [
{
name: 'this is name1',
description: 'desc 1'
},
{
name: 'this is name 2',
description: 'desc 2'
},
{
name: 'this is name 3',
description: 'desc 4'
}
]
$scope.changeSelected = function (index) {
$scope.selectedItem = $scope.items[index];
}
$scope.changeSelected(0);
$scope.update = function () {
console.log($scope.items);
}
}
you can look it at here:
http://jsfiddle.net/9c567te7/

How to dynamically create a form using angularjs

I am trying to figure out how to dynamically create a form based on an array of fields returned from the server.
Something like this
[{
id: "title",
type: "text", /* Map to Input type=text */
regex: "/^[a-zA-Z]+/"
},{
id: "summary",
type: "memo", /* Map to Textarea */
regex: "/^[a-zA-Z]+/"
},{
id: "priority",
type: "list", /* Map to Select */
options: [1,2,3,4,5]
}]
I cant figure out a nice way of doing this, even with ng-repeat. Once the form has about 30 fields, and 15+ different input types, it gets very ugly.
Whats the 'Angular' way to do this, or should i generate the controller.js and template.html dynamically on the server?
Try this. It is not the answer, just an approach.Hope It may help You.
HTML:
<div ng-repeat="person in person">
<form class="form-group" name="signinForm">
<label>Name:
<input class="form-control" ng-model="person.name" type="text">
</label>
<label>Male:
<input class="form-control" ng-model="person.gender" name="gender{{$index}}" type="radio" value="male">
</label>
<label>Female:
<input class="form-control" ng-model="person.gender" name="gender{{$index}}" type="radio" value="female">
</label><br>
<label>Age
<input class="form-control" ng-model="person.age" type="number">
</label>
</form>
<button type="button" ng-click="addPerson()">Add More</button>
</div>
JS:
$scope.initialize = [{}];
$scope.person = {};
$scope.addPerson = function(){
$scope.initialize.push({});// adding more similar fields.
}

Serialize form to a specific json format

When I use .serializeArray(), my data looks like:
[ Object { Name="Name", Value="MyName" }, Object { Name="Age", Value="15"} ]
But I want it to look like:
{ Name: "MyName", Age: 15 }
What do I need to do?
My form:
<form id="newUser">
<input id="Name" name="Name" />
<input id="Age" name="Age" />
<input type="submit" />
</form>
You could write a bit of code which takes the first format and then converts it into the other. Just have it loop over the array and take Name as a key in the object, and Value as the value for the key and assign each pair into a single object.

Categories

Resources