Convert Form data to JSON - javascript

<html>
<head></head>
<body>
<form name="abc" action="#" method="post">
Name: <input type="text" name="name"><br>
Age : <input type="text" age="name"><br>
<input type="submit"><br>
</form>
</body>
</html>
Can any one write this HTML code in such a way that when I will submit this form the the form data will be submitted in JSON format .

A pure JavaScript solution would be:
var form = document.getElementsByTagName('form')[0];
form.addEventListener('submit',function(event){
event.preventDefault();
var data = {
"name":this.name.value,
"age":this.age.value
};
console.log(data);
});

Try substituting name="age" for age="name" at second input type="text" , utilizing .serializeArray() , $.post()
$("form").submit(function(e) {
e.preventDefault();
var data = $(this).serializeArray();
console.log(data);
// $.post("/path/to/server", data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<form name="abc" action="#" method="post">
Name:
<input type="text" name="name">
<br>Age :
<input type="text" name="age">
<br>
<input type="submit">
<br>
</form>

check this function
var formDataToObject = function (formElm) {
var formObj = new FormData(formElm),
result = {},
values = formObj.values(),
keys = formObj.keys(),
key;
while (!(key = keys.next()).done) {
result[key.value] = values.next().value;
}
return result;
};
Two notes here:
1) No support for multiple select options, it will return the last selected option!!
2) The loop breaks when the next() return object with done equals to true,
but this object also contains the key for the last element in the form
which is in most cases the Submit Button, so if you don't have one in the form the last element will be excluded, easy to fix.

Related

Dynamically pass in values to the data object

Currently, I get the value of an id and pass it in my data object to be sent to the server.
const field_value = $('#id_field').val();
const scores_value = $('#id_scores').val();
$.ajax({
data: {'Fields':field_value, 'Scores': scores_value},
});
I want to achieve this dynamically in case I add more forms so it can automatically update without me having to change any code.
I tried using the jquery each method to access the class.
$(".class").each(function() {
const get_updated_value = $(this).val();
});
This dynamically gets the values, but I am having trouble passing the returned values to the data object.
If each element with '.class' has still an own id you could take these id's as the keys of the data object:
var updated_values = {};
$(".class").each(function() {
updated_values[$(this).attr('id')] = $(this).val();
});
$.ajax({
data: updated_values,
});
Working example:
function update() {
var updated_values = {};
$(".input").each(function() {
updated_values[$(this).attr('id')] = $(this).val();
});
console.log(updated_values);
}
input {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="text" placeholder="My task" id="field" class="input">
<input type="text" placeholder="My date" id="scores" class="input">
<input type="text" placeholder="My time" id="something_new" class="input">
<input type="button" value="Update" onclick=update() id="save">
</div>

HTML Form input into Javascript array

My goal is to enter a single name into a html Text form. Each time I press submit
it will store that value into a javascript array. Currently, I am able to get
the first value I submit into the array but not the subsequent values. Hope I am
being clear enough, Any help would be great.
Here is my JavaScript
function getListOfNames() {
"use strict";
//Declare variables
var form;
var getNameValue;
var myArray = [];
var output;
//Assign values
output = document.getElementById("myTable");
form = document.getElementById("myForm");
getNameValue = form.getNameValue.value;
//Each time form is submited put the new value into array
myArray.push(getNameValue);
//output the results
output.innerHTML = myArray;
}
function project5Part2() {
"use strict";
// Your code goes in here.
getListOfNames();
return false;
}
Here is my HTML
<form id="myForm" action="#" onsubmit=" return project5Part2();" >
<label for="firstName">Enter Name</label>
<input type="text" id="enteredName" name="getNameValue"/>
<input type="submit" value="Enter Name" />
<input type="reset"  value="Clear form - DO NOT SEND" />
</form>
Remove the onsubmit from the form.
change the input type="submit" into a regular button and use the onclick to execute JavaScript.
<form id="myForm" action="#" >
<label for="firstName">Enter Name</label>
<input type="text" id="enteredName" name="getNameValue"/>
<button type="button" onclick="project5Part2();">Enter Name</button>
<input type="reset" value="Clear form - DO NOT SEND" />
</form>
Create or use a global array (cannot be enclosed in the method if you want to persist)
When the button is clicked, checked the value of the textbox and if not empty, add the value to the array.
var myArray = new Array();
function project5Part2() {
var name = document.getElementById('enteredName').value;
if (!(typeof name === 'undefined') && name!=null && name.trim()!='') {
myArray.push(name);
}
console.log(myArray);
document.getElementById('enteredName').value = '';
}
Will log the contents of the array each time the button is clicked.
For example: ["albert", "manny", "susan"]
The textbox value is being cleared each time the name is added.

Get data for form input array using specific key

So, let's say I have an HTML form like this:
<form id="myForm">
<input type="text" name="dummy">
<input type="text" name="people[0][first_name]" value="John">
<input type="text" name="people[0][last_name]" value="Doe">
<input type="text" name="people[1][first_name]" value="Jane">
<input type="text" name="people[1][last_name]" value="Smith">
</form>
And I want to get a JavaScript array that matches the values of real. For example:
// If there was a sweet function for this...
var people = getFormDataByInputName( 'people' );
// Value of `people` is...
// [
// {
// 'first_name' : 'John',
// 'last_name' : 'Doe'
// },
// {
// 'first_name' : 'Jane',
// 'last_name' : 'Smith'
// }
// ]
Is there any easy way of doing that for just a specific form item (in this case, people)? Or would I have to serialize the entire form an then just extract the element I want?
I also thought of potentially using the following approach:
var formData = new FormData( document.querySelector( '#myForm' ) );
var people = formData.get( 'people' );
But that doesn't appear to work; people is just null after that.
You could do this with plain js using reduce method and return each person is one object.
const form = document.querySelectorAll('#myForm input');
const data = [...form].reduce(function(r, e) {
const [i, prop] = e.name.split(/\[(.*?)\]/g).slice(1).filter(Boolean)
if (!r[i]) r[i] = {}
r[i][prop] = e.value
return r;
}, [])
console.log(data)
<form id="myForm">
<input type="text" name="dummy">
<input type="text" name="people[0][first_name]" value="John">
<input type="text" name="people[0][last_name]" value="Doe">
<input type="text" name="people[1][first_name]" value="Jane">
<input type="text" name="people[1][last_name]" value="Smith">
</form>
function getObject(name, key) {
if(key.includes(name)) {
var splitStr = key.split(/\[|\]/g);
return {
index: splitStr[1],
key: splitStr[3],
}
}
return null;
}
function getFormDataByInputName(name) {
var formData = new FormData( document.querySelector('#myForm'));
var results = [];
for (var key of formData.keys()) {
var obj = getObject(name, key);
if (obj) {
if (results[obj.index]) results[obj.index][obj.key] = formData.get(key);
else results[obj.index] = { [obj.key]: formData.get(key) };
}
}
return results;
}
var people = getFormDataByInputName('people');
console.log(people);
<form id="myForm">
<input type="text" name="dummy">
<input type="text" name="people[0][first_name]" value="John">
<input type="text" name="people[0][last_name]" value="Doe">
<input type="text" name="people[1][first_name]" value="Jane">
<input type="text" name="people[1][last_name]" value="Smith">
</form>
Your code won't work because to HTML/JS name is just a string that it sends to the server when the form is submitted (the name in the name/value pairs). You might think it is arrays, but HTML/JS doesn't.
So no one-liner to get the job done. Try this: In your HTML, add <div class="name"> ...
(UPDATE: thanks for the idea, #Nenad, I've never tried one of these snippets)
var people = [];
$('.name').each(function() {
people.push({
first_name: $('input:nth-child(1)', this).val(),
last_name: $('input:nth-child(2)', this).val()
});
});
console.log(people);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="text" name="dummy">
<div class="name">
<input type="text" value="John">
<input type="text" value="Doe">
</div>
<div class="name">
<input type="text" value="Jane">
<input type="text" value="Smith">
</div>
</form>
Use CSS attribute prefix selector, such as
form.querySelectorAll('[name^="people[]"]')
You can use a for-loop to get all peoples, as such
const MAX_PEOPLES = 2;
const list = [];
for (i = 0; i <= MAX_PEOPLES; i++) {
const eles = form.querySelectorAll(`[name^="people[${i}]`);
if (eles.length !== 2)
break;
list.push({
first_name: eles[0].value,
last_name: eles[1].value
});
}
that yields
[
{
"first_name":"John",
"last_name":"Doe"
},
{
"first_name":"Jane",
"last_name":"Smith"
}
]

Process a form with javascript and use it in pop up?

Theres a form on a website I'm trying to make and I was wondering if there was a way to click the submit button for the form and then have a pop up use that information
sorry for the newb question, code is kind of like this:
<form name="myform" onsubmit="submitform()" type="POST">
Username: <input type="text" name="username">
<a>
<input type = "submit" value = "Submit"
</a>
</form>
<script type="text/javascript">
function submitform()
{
username = document.getElementsByName("username")
window.alert("hi:" username)
}
</script>
Yeah, there's a few issues with your code, but you're close.
Submit buttons shouldn't be inside of <a> tags. You're also missing the closing carrot here.
You're using type, but I'm guessing you meant method.
In your JavaScript, you're getting an array of elements with getElementsByName and never getting the value.
Put that all together, and:
<form name="myform" onsubmit="submitform()" method="POST">
Username: <input type="text" name="username" />
<input type="submit" value="Submit" />
</form>
<script>
function submitform()
{
username = document.getElementsByName("username")[0].value
window.alert("hi:" username)
return false;
}
</script>
You can try this:
<form name="myform" onsubmit="submitform(this) return false;" type="POST">
then in your function:
function submitform(form)
{
username = document.getElementsByName("username")
window.alert("hi:" username)
}
Then use the form object your passing in.
if ($(form).valid())
{
var fields = $(form).serializeArray();
$(fields).each(function ()
{
if (this.name !== undefined)
{
var propertyName = this.name;
var propertyValue = this.value;
//Do something
}
});
}

How can to show more than one form value in a alert?

I'm submitting a form which its deleting record.
It's a simple checkbox, if the user check the box then
that record will be deleted from the table , which works.
What I would like to do its have a alert box which shows
the name of the person(s) they are deleting before and then they confirm it which then it will be deleted.
Right now im using ajax to show the alert but its only showing the first record I check ,
It still deleting all the records but I would like it to show all all the names before the user confirm it.
How would I be able to accomplish this?
function sub_keys()
{
alert_string='Are you sure you want to delete ';
var con=confirm( alert_string + document.getElementById("name_id").value + '?');
if(con)
{
var formData = $("#confrm_key").serializeArray();
var URL = 'quality_time_delete_table2.cfc?method=getkeyDetail';
more code.....
}
form:
<input type="hidden" name="name_Id" id="name_id" value="#emp_namefirst# #emp_namelast# ">
You can add a class in your checkboxes and use js querySelectorAll and Array.prototype.map():
var text = document.querySelectorAll('.name');
var values = [].map.call(text, function(obj) {
return obj.innerHTML;
});
confirm(values);
<div class="name">test1</div>
<div class="name">test2</div>
<div class="name">test3</div>
<div class="name">test4</div>
And one example close to your needs:
function deletePeople() {
var text = document.querySelectorAll('input[type=checkbox]:checked');
var values = [].map.call(text, function (obj) {
return obj.value;
});
var res = confirm(values);
res ? alert("records deleted") : alert("no action");
}
<input type="checkbox" value="test1" />
<input type="checkbox" value="test2" />
<input type="checkbox" value="test3" />
<input type="checkbox" value="test4" />
<input type="button" onclick="deletePeople();return false;" value="Delete" />
Also keep in mind that id must be unique.
References:
Array.prototype.map()
document.querySelectorAll

Categories

Resources