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
Related
I use Javascript to intercept an HTML form submission:
var form_api = $("#apiForm");
$(form_api).submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* Get input values from form */
var formData = prepFormData("#apiForm");
}
However, when I convert the data into an object (I wish to use jQuery to pass this to an endpoint), all object properties are strings.
function prepFormData(formSelector){
var form_api = $(formSelector);
// Serialize the form data as a PlainObject.
var formData = $(form_api).serializeArray().reduce(function (obj, item) {
obj[item.name] = item.value;
return obj;
}, {});
}
Why does it always produce strings? I would like the following behavior instead:
<input type="text"> should produce NULL when nothing has been entered.
<input type="number"> should produce an Int when a value has been entered.
You need to parse the input to suite your needs. Every form value in HTML in inherently a string.
The type attribute lets the browser know what kind of field to display, not what is the data type of the value. Take for example:
<input type="hidden" value="1">
HTML and javascript can infer no information about the data type from hidden it could be a string it could be an int.
number is equally problematic, why default to int, what about doubles and other number types?
In my example above, note that the value is surrounded by quotes, denoting a string. (Quotes are optional, but recommended, but do nothing to the data type.)
To actually solve your problem I would consider adding a data attribute to your fields, say data-type to hold the data type you want to cast your value to.
Here's a quick example:
var form_api = $("#apiForm");
$(form_api).submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* Get input values from form */
var formData = prepFormData("#apiForm");
console.log(formData);
});
function prepFormData(formSelector){
var form_api = $(formSelector);
// Serialize the form data as a PlainObject.
var formData = $(form_api).serializeArray().reduce(function (obj, item) {
var tempValue = null;
if(item.value !== "") {
//Get data type of current field
var dataType = $(form_api).find("[name=" + item.name + "]").data("type");
if(dataType === undefined) {
dataType = "text";
}
//Extend this based on the other data types you need
switch(dataType) {
case "text" :
tempValue = item.value;
break;
case "int" :
tempValue = parseInt(item.value, 10);
break;
case "float" :
tempValue = parseFloat(item.value);
break;
//Fall back for no data type defined, eg the select in this example
default :
tempValue = item.value;
break;
}
}
obj[item.name] = tempValue;
return obj;
}, {});
return formData;
}
label {display:block; margin-bottom:5px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<form id="apiForm" method="get" action="">
<label>Name <input type="text" data-type="text" name="Name"></label>
<label>Integer <input type="number" data-type="int" name="Integer"></label>
<label>Float <input type="number" step="0.1" data-type="float" name="Float"></label>
<fieldset>
<legend>Age Range</legend>
<label><18 <input type="radio" data-type="text" name="AgeRange" value="<18"></label>
<label>>18 <input type="radio" data-type="text" name="AgeRange" value=">18"></label>
</fieldset>
<label>Country
<select name="country">
<option value="usa">USA</option>
<option value="aus">Australia</option>
<option value="other">Other</option>
</select>
</label>
<label>Product
<select name="ProductId" data-type="int">
<option value="1">Apple</option>
<option value="2">Orange</option>
<option value="11">Pear</option>
<option value="110">Pineapple</option>
</select>
</label>
<input type="hidden" data-type="text" name="HiddenText" value="">
<input type="submit">
</form>
This in normal JS behaviour. type number and text are for validations inside the input for browsers. They don't define the data-type of the value inside of them. By default they are strings. You can perform conversions for your use. The text field returns an empty string because it's by default an empty string and not null.
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.
I create a function in which my input values of form are being collected in an object then afterwards I push whole object in an array and save my array in local Storage...But the problem is when I change the value and sign up again my old values are overwritten with new one but I want it to push on index 1 of array so that my array contain 2 objects and so on... Please help me Thanking You.
<script>
var labelsarray = document.getElementsByTagName("label");
var inputsarray = document.getElementsByTagName("input");
var array = [];
function subm() {
var users = {
FirstName: inputsarray[0].value,
LastName: inputsarray[1].value,
UserName: inputsarray[2].value,
Password: inputsarray[3].value,
DateofBirth: inputsarray[4].value,
Age: inputsarray[5].value,
Purpose: ""
};
if (inputsarray[6].checked === true) {
users.Gender = "Male";
}
else if (inputsarray[7].checked === true) {
users.Gender = "Female";
}
if (inputsarray[8].checked === true) {
users.Purpose += " Storing Apps";
}
if (inputsarray[9].checked === true) {
users.Purpose += " Storing Sites";
}
if (inputsarray[10].checked === true) {
users.Purpose += " Fun";
}
array.push(users);
for (var i=0;i<array.length;i++) {
localStorage.setItem("User Data: ", JSON.stringify(array[i]));
}
}
</script>
<div>
<center>
<form action="Javascript:void(0);"method="post" onsubmit="subm();">
<label for="fname">First Name:</label>
<input type="text" id="fname" />
<br/>
<label for="lname">Last Name:</label>
<input type="text" id="lname" />
<br/>
<label for="uname">User Name:</label>
<input type="text" id="uname" />
<br/>
<label for="pass">Password:</label>
<input type="text" id="pass" />
<br/>
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" />
<br/>
<label>Age:</label>
<input type="text" id="age" />
<br/>
<span>Gender:</span>
<input type="radio" name="gender" id="male" />
<label for="male">Male</label>
<input type="radio" name="gender" id="female" />
<label for="female">Female</label>
<br/>
<p>For what purpose(s) you are making account?</p>
<input type="checkbox" id="app" name="purpose" value="storingapps" />
<label for="app">Storing Apps</label>
<input type="checkbox" id="site" name="purpose" value="storingsites" />
<label for="site">Storing Sites</label>
<input type="checkbox" id="fun" name="purpose" value="fun" />
<label for="fun">Fun</label>
<br/>
<input type="submit" value="Submit" class="button" />
</form>
</center>
</div>
Each time you save in your local storage you are saving just the last item. Because each save will be replaced by the next one and only the last one would be visible. Instead you only need to save the array into the local storage
// (not needed) for (var i=0;i<array.length;i++) {
localStorage.setItem("User Data: ", JSON.stringify(array));
// (not needed) }
Now your local storage will have array of objects
You're recreating your array every time instead of reading it from Local Storage. As such, you're starting with a fresh array every time.
Where you're doing var array = []; you should be reading from local storage.
For example:
var array = [];
var savedArrayJSON = localStorage.getItem("userData");
if (savedArray) {
try {
array = JSON.parse(savedArrayJSON);
} catch (e) {
// Probably do nothing
}
}
...
array.push(users);
// No more for-loop
localStorage.setItem("userData", JSON.stringify(array));
After you set up your array, you loop through it and upon each iteration you are overwriting the User Data key from the last iteration in localStorage, so only the last array item is getting stored:
for (var i=0;i<array.length;i++) {
localStorage.setItem("User Data: ", JSON.stringify(array[i]));
}
You should just set the entire array into local storage or make distinct keys to store the individual items with:
localStorage.setItem("User Data: ", JSON.stringify(array));
Next, each time someone comes to your page, you create a new, empty array, so when does the data in localStorage ever get pulled out and used? Upon page access, you should be getting the saved data so that you can push more into it:
// Set the array variable equal to the array in localStorage or an empty array
var array = JSON.parse(localStorage.getItem("User Data")) || [];
ADDITIONAL NOTES:
Your HTML is not valid and follows out of date methodologies.
Javascript:void(0);
Is not only mis-capitalized (should be: javascript:void()), but that entire technique for doing nothing shouldn't be used as well as onsubmit (HTML event handling attributes). All your JavaScript should be in dedicated scripts and event handling should be done using element.addEventListener().
<center> is deprecated. All formatting should be done with CSS.
<input> and <br> elements should not use the XML self-terminating syntax of /> at the end of the tag. While this is legal, it is a left-over relic of 2000 when the world thought that XML was going to be the future. It buys you nothing in your code and can lead to bugs when not used correctly.
You can try the following code.This occurs because you are overwriting the localStorage values everytime you are creating a new user.A simple solution is to store the users in array format and appending new users to it everytime a new user fill up form and then save it to the localStorage.
```
<script>
var labelsarray = document.getElementsByTagName("label");
var inputsarray = document.getElementsByTagName("input");
//Here We first Grab the already stored value from the localStorage and parse it because it is in string format.
var array = JSON.parse(localStorage.getItem('User Data: ')) || [];
function subm() {
var users = {
FirstName: inputsarray[0].value,
LastName: inputsarray[1].value,
UserName: inputsarray[2].value,
Password: inputsarray[3].value,
DateofBirth: inputsarray[4].value,
Age: inputsarray[5].value,
Purpose: ""
};
if (inputsarray[6].checked === true) {
users.Gender = "Male";
}
else if (inputsarray[7].checked === true) {
users.Gender = "Female";
}
if (inputsarray[8].checked === true) {
users.Purpose += " Storing Apps";
}
if (inputsarray[9].checked === true) {
users.Purpose += " Storing Sites";
}
if (inputsarray[10].checked === true) {
users.Purpose += " Fun";
}
//We Now append the users to the array and save it to localStorage.
array.push(users);
localStorage.setItem("User Data: ", JSON.stringify(array));
}
```
I hope this works for you also.
I want to get an Object in javascript with values from my dynamically generated array in correct order so then later on I will be able to jsonencode that object and save it into my Database. (Maybe there is a different easier way of doing it)
Here is the form
<form name="second_form" id="second_form" action="#" method="POST">
Add Champion
<div id="ChampionInput">
</div>
<input type="submit" name="submit">
</form>
Here are functions that I use to create this array:
$('a#AddChampion').on('click',function(){
$('div#ChampionInput').append(
'<div class="Champion">\
<input type="text" class="ChampionInput">\
Add General Change\
<div class="GeneralChanges">\
</div>\
<div>');
});
$('div#ChampionInput').on('click','a.AddGeneralChange', function(){
$(this).siblings('.GeneralChanges').append(
'<div class="GeneralChange">\
<textarea type="text" size="20" rows="3" cols="50" class="GeneralChangeDescription"></textarea>\
</div>');
});
And below is what I've tried with no result. I was trying to loop through values of my array and then put it into an object I get the whole div instead of the actual value.
$( "#second_form" ).submit( function(event) {
$( "#ChampionInput.ChampionInput :input" ).each( function( index, value ) {
var _value = value;
var _index = index;
alert(value);
$(this).children( ".GeneralChangeDescription").each( function( index, value ) {
});
});
});
Here is a picture of how it could look like after adding some fields http://imgur.com/QXhWSHA
And here is working jSfiddle: http://jsfiddle.net/ss84agxv/
Try this code, I hope that I understood your question correctly.
$("#second_form").submit(function(event) {
//don't do the default action on submit
event.preventDefault();
//Your object as array for the champions
var object = [];
//Loop through each .Champion-div
$('.Champion').each(function() {
//Create a new object for this champion with the value from the input field and an array for the descriptions
var champion = {
'name': $(this).find(".ChampionInput").val(),
'description': []
};
//Loop through each description textfields of this champion
$(this).find('.GeneralChangeDescription').each(function() {
//add the description to the description array of the champion
champion.description.push($(this).val());
});
//finally put the champion in your champion array
object.push(champion);
});
//Thats just for you, an alert of the json-object
alert(JSON.stringify(object));
});
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/