Form input to JavaScript Object - javascript

I'm familiar with JavaScript, but not familiar with using it in the DOM. I'm trying to make a form that will accept an item name + properties and store it like I'm writing out the object below:
var grocery_list = {
"Banana": { category: "produce", price: 5.99 },
"Chocolate": { category: "candy", price: 2.75 },
"Wheat Bread": { category: "grains and breads", price: 2.99 }
}
Here is the sample HTML Form I have:
<form>
<input name="item"><br>
<input name="category"><br>
<input name="price"><br>
<input type="submit" value="do stuff">
</form>
How can I use JavaScript take the input above and push it to an Object (like above)?

Add a listener to the form, collect the values, build an object and add it to the grocery_list, e.g.
<script>
var grocery_list = {}
function addGroceryItem(form) {
grocery_list[form.item.value] = {category: form.category.value, price: form.price.value};
return false;
}
</script>
<form onsubmit="return addGroceryItem(this)">
<input name="item"><br>
<input name="category"><br>
<input name="price"><br>
<input type="submit" value="Add item">
<input type="button" value="Show list" onclick="console.log(grocery_list)">
</form>
Though I'd be tempted to use a plain button, not a submit button, and put the listener on the button's onclick handler.

This could be easily done with jQuery:
var objects = [];
$('form').on('submit', function(e){
var item = $('#item').val(), category = $('#category').val(), price = $('#price').val();
objects.push({item:{'category':category, 'price':parseFloat(price)}});
console.log(JSON.stringify(objects));
e.preventDefault();
});
By listenting to a submit event on the form, populating the object and pushing it to an object array. about reading the values from DOM, see the $('#input_id').val() which takes these values.
Assuming you though about pure JS, this could also be done:
var objects = [];
var form = document.getElementById('form');
form.onsubmit = function(e){
var item = document.getElementById('item').value, category =document.getElementById('category').value, price = document.getElementById('price').value;
objects.push({item:{'category':category, 'price':parseFloat(price)}});
console.log(JSON.stringify(objects));
e.preventDefault();
}
http://jsfiddle.net/70fnct9c/
UPDATE
as robg noted, storing the objects in an object instead of array could also be done easily:
var objects = {}
................
................
objects[item] = {'category':category, 'price':parseFloat(price)}
http://jsfiddle.net/70fnct9c/2/

Related

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.

Comma seperates objects

I have inputs where user can enter numbers and whenever user puts comma between numbers I want to make new Object.
For example, user insert "23, 24, 25" and presses enter, I want to get 3 objects(23, 24, 25) and push them in array.
I am not sure if this is what you want, but you could use a html form to trigger a function like this:
var myArray = [];
function createObject(id) {
return {
id: id
}
}
function pushToObjArray() {
document.getElementById("objectIds").value
.split(",").forEach(function(id) {
var myObj = createObject(id);
myArray.push(myObj);
});
console.log(myArray);
}
<form action="javascript: pushToObjArray()">
<input type="text" id="objectIds" />
<input type="submit" value="GO!">
</form>
Fiddle: https://jsfiddle.net/qydkpmrw/
Reference Link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
str.split(separator) will return array for you.
let input = "23,24,25";
let data = input.split(",");
console.log(data);

How can I use this autofill feature from json with dynamically created inputs?

I'm using this autofill function which grabs a value from the input descricaoItem(description), send it to a query and fill the other input field with the codigo(code) value, from the database. The code is below:
$(document).ready(function() {
$('#descricaoItem0').change(function () {
$.post('mandaDescricao.php',
{
descricao: document.getElementById('descricaoItem0').value
},
function(data){
var obj = $.parseJSON(data);
$('#codigoItem0').val(obj.codigo);
});
});
});
This one works fine, but I want to create those inputs dynamically, when the user presses a button. Already have this function, and the inputs are created with different ID's (descricaoItem0, descricaoItem1, and so on...) which are related with (codigoItem0, codigoItem1,...). But, with these inputs dynamically created I can't find a way to use the above function.
Could you please, help me? I don't want to copy and paste this function 'till descricaoItem20.
Wrap your event assigner in a function!
Every time a new input is added, fire this function and pass the correct id number.
function assignOnChangeToInput(id) {
$('#descricaoItem' + id).change(function() {
$.post('mandaDescricao.php', {
descricao: document.getElementById('descricaoItem' + id).value
},
function(data) {
var obj = $.parseJSON(data);
$('#codigoItem' + id).val(obj.codigo);
});
});
});
}
Create a JSON object that consists of an Array of Input Objects.
[ {id: '#codigoItem0'}, {id: '#codigoItem1'}, {id: '#codigoItem2'} ]
Use a forEach loop to apply the change event listener to each individual node.
var JSONObj = [ {id: '#codigoItem0'}, {id: '#codigoItem1'}, {id: '#codigoItem2'} ]
JSONObj.forEach(function(input) {
var id = input.id;
$(id).change(function(e) {
$.post('mandaDescricao.php',
{
descricao: document.getElementById(id).value
},
function(data){
var obj = $.parseJSON(data);
$(id).val(obj.codigo);
});
});
})
})
Might be worth making a more detailed JSON Array of inputs where an input-Object might look like :
{
id: 'inputID',
name: 'inputName'
val: 'Foo',
placeholder: 'Bar',
callback: '_aCallbackMethod()'
}
And then you can create input elements based on an Array of those detailed inputs and handle them as Objects rather than needing to query the DOM so much with $(blah). :-)
You don't need to use the ID (which will help with your dynamic problem) You can add the event to all inputs with a class and then use this inside the input change event for the input the user is interacting with, for example
<input class="descricaoItem" />
<input class="descricaoItem" />
<input class="descricaoItem" />
<input class="descricaoItem" />
<input class="descricaoItem" />
$(document).ready(function() {
$('.descricaoItem').on("input", function() {
var descricaoValue = $(this).val();
var self = this; // save context of this
$.post('mandaDescricao.php', {
descricao: descricaoValue
},
function(data) {
var obj = $.parseJSON(data);
$(self).val(obj.codigo);
});
});
});
Here is a minimal example (without the POST request)
$(document).ready(function() {
$('.descricaoItem').on("input", function() {
var descricaoValue = $(this).val();
var self = this; // save context of this
$(self).val("codigo obj: " + Math.floor(Math.random() * 100) + 1);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="descricaoItem" />
<input class="descricaoItem" />
<input class="descricaoItem" />
<input class="descricaoItem" />
<input class="descricaoItem" />

how to convert variable name into index string of object jquery

when I make a looping based on the content in the form of an input form
I'll take the attribute name to be used as a selector element and object index array of data, but the index is the variable name
how to convert from a variable name to string index on an object array
of data?
it aims to make input in the form can be filled automatically from the object array of data
var data = {
id: "4",
Model: "804",
Description: "AXIAL SETTER,100MM, MAGNETIC BASE"
};
var names = [];
if ($('#form').length == 1) {
$('#form :input').each(function() {
names.push($(this).attr('name'));
});
$.each(names, function(key, value) {
$('[name="' + value + '"]').val(data.value);
//value should be change with name,
//for example :
// $('name="Description"').val(data.Description);
});
}
<form action="#" id="form" class="form-horizontal">
<input type="hidden" name="id" />
<br/>
<input type="text" name="Model" placeholder="Model Of product" />
<br/>
<input type="text" name="Description" placeholder="Description Of product" />
<br/>
<button type="submit" class="btn-save">save</button>
</form>
No need to run twice over the same data. You could simply do this to fill your form:
var data = {
id: "4",
Model: "804",
Description: "AXIAL SETTER,100MM, MAGNETIC BASE"
};
if ($('#form').length == 1) {
$('#form :input').each(function() {
if (typeof data[$(this).attr('name')] != 'undefined'){
$(this).val(data[$(this).attr('name')]);
}
});
}
Have a look at https://jsfiddle.net/nfq22d9r/1/
The code runs through all the forms input fields, checks if a fields name is existent as a key in the data object and sets the fields value to the one in the data object, if the key was found

adjusting default value script to work with multiple rows

I am using a default value script (jquery.defaultvalue.js) to add default text to various input fields on a form:
<script type='text/javascript'>
jQuery(function($) {
$("#name, #email, #organisation, #position").defaultvalue("Name", "Email", "Organisation", "Position");
});
</script>
The form looks like this:
<form method="post" name="booking" action="bookingengine.php">
<p><input type="text" name="name[]" id="name">
<input type="text" name="email[]" id="email">
<input type="text" name="organisation[]" id="organisation">
<input type="text" name="position[]" id="position">
<span class="remove">Remove</span></p>
<p><span class="add">Add person</span><br /><br /><input type="submit" name="submit" id="submit" value="Submit" class="submit-button" /></p>
</form>
I am also using a script so that users can dynamically add (clone) rows to the form:
<script>
$(document).ready(function() {
$(".add").click(function() {
var x = $("form > p:first-child").clone(true).insertBefore("form > p:last-child");
x.find('input').each(function() { this.value = ''; });
return false;
});
$(".remove").click(function() {
$(this).parent().remove();
});
});
</script>
So, when the page loads there is one row with the default values. The user would then start adding information to the inputs. I am wondering if there is a way of having the default values show up in subsequent rows that are added as well.
You can see the form in action here.
Thanks,
Nick
Just call .defaultValue this once the new row is created. The below assumes the format of the columns is precticable/remains the same.
$(".add").click(function() {
var x = $("form > p:first-child");
x.clone(true).insertBefore("form > p:last-child");
x.find('input:not(:submit)').defaultvalue("Name", "Email", "Organisation", "Position");
return false;
});
You should remove ids from the input fields because once these are cloned, the ids, classes, everything about the elements are cloned. So you'll basically end up with multiple elements in the DOM with the same id -- not good.
A better "set defaults"
Personally I would remove the "set defaults plugin" if it's used purely on the site for this purpose. It can easily be re-created with the below and this is more efficient because it doesn't care about ordering of input elements.
var defaults = {
'name[]': 'Name',
'email[]': 'Email',
'organisation[]': 'Organisation',
'position[]': 'Position'
};
var setDefaults = function(inputElements)
{
$(inputElements).each(function() {
var d = defaults[this.name];
if (d && d.length)
{
this.value = d;
$(this).data('isDefault', true);
}
});
};
Then you can simply do (once page is loaded):
setDefaults(jQuery('form[name=booking] input'));
And once a row is added:
$(".add").click(function() {
var x = $("form > p:first-child");
x.clone(true).insertBefore("form > p:last-child");
setDefaults(x.find('input')); // <-- let the magic begin
return false;
});
For the toggling of default values you can simply delegate events and with the help of setDefault
// Toggles
$('form[name=booking]').delegate('input', {
'focus': function() {
if ($(this).data('isDefault'))
$(this).val('').removeData('isDefault');
},
'blur': function() {
if (!this.value.length) setDefaults(this);
}
});
Fiddle: http://jsfiddle.net/garreh/zEmhS/3/ (shows correct toggling of default values)
Okey, first of all; ids must be unique so change your ids to classes if you intend to have more then one of them.
and then in your add function before your "return false":
var
inputs = x.getElementsByTagName('input'),
defaults = ["Name", "Email", "Organisation", "Position"];
for(var i in inputs){
if(typeof inputs[i] == 'object'){
$(inputs[i]).defaultvalue(defaults[i]);
}
}

Categories

Resources