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.
Related
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 want to convert all form values to JSON so that I can send the JSON as body in my AJAX POST. I found this existing solution online:
function getFormData($form){
var unindexed_array = $form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function(n, i){
indexed_array[n['name']] = n['value'];
});
return indexed_array;
}
Usage:
var $form = $("#form_data");
var data = getFormData($form);
However, this approach (source) converts all values to type string, it does not preserve numbers as integers. I could not come up with a way to preserve the type of the values. What is the best way to do this?
HTML:
<form id="myform">
<div>
<label>Number: </label>
<input id="mynum" type="number" name="mynum"/>
</div>
<div>
<label>name: </label>
<input id="myname" type="text" name="myname"/>
</div>
</form>
That is because all input values are by default of type string. If you want to convert the type to number type you have to do that manually.
One way to do that by looping through the JSON and use a manual function to parse string value back to the number type.
To create a manual function: http://pietschsoft.com/post/2008/01/14/JavaScript-intTryParse-Equivalent
The following code shows even if the input type is number, the type is actually string:
let type;
function checkFormData(){
type = document.getElementById('mynum').value;
console.log('The type of input#mynum is: ' +typeof type);
return false;
}
<form id="myform" onsubmit=" return checkFormData()">
<div>
<label>Number: </label>
<input id="mynum" type="number" name="mynum"/>
</div>
<div>
<label>name: </label>
<input id="myname" type="text" name="myname"/>
</div>
<input type="submit" value="Submit"/>
</form>
My form looks like this.
<form>
<input type="text" name="pic" value="test" />
<input type="text" name="person[0].name" value="Bob" />
<input type="text" name="person[0].age" value="25" />
<input type="text" name="person[1].name" value="Jim"/>
<input type="text" name="person[1].age" value="30" />
</form>
Is their a method that can take in any form and if the name of several form elements is the same then make them into an array under the initial name in json.
The json object would ideally look like
{
"pic" : "test",
"person":[
{"name":"Bob", "age":"25"},
{"name":"Jim", "age":"30"}
]
}
I found a library that handles this
form2js
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.
In tornado's template in I passed from code dictionary data with keys username and code
data = {'username' : 'pal', 'code' : 16281}
in ready function I am trying to set passed values to two inputs on page
$(document).ready(function() {
var d = "{{data}}";
alert(d);
$('#code').val({{data['code']}});
$('#username').val(d['username']);
});
...
<label for="username" class="ui-hidden-accessible">Username:</label>
<input type="text" placeholder="Username" name="username" id="username" class="large_input">
<label for="code" class="ui-hidden-accessible">Code:</label>
<input type="text" placeholder="Code" name="code" id="code" class="large_input">
Alert shows that dictionary is ok, but when I try to access on any way I got undefined value. I tried with passed data and with js dictionary d but it didn't work.
How to set passed values into template's fields ?
For HTML this would work:
<input value="{{data["username"]}}" type="text" placeholder="Username" name="username" id="username" class="large_input">
For your JS I image you need to write this instead:
$('#code').val('{{data['code']}}');