I have an array and it has some data in it. This array contains id, firstname, lastname, email, phone. I also have five form input elements. Now I want to add data in array in these elements. For example, ID should be inserted in ID form field, name should be inserted in name input element etc. how can I achieve this?
here is my code
insert_data_in_form: function(data) {
var form = $("#dataform");
var form_arr = new Array();
form.each(function(i) {
var form_el = form.children("input[type='textfield']");
form_arr.push(form_el);
console.log(data.length);
//for(var j = 0; j < 5; j++) {
form_el.val(data[i]);
//}
});
}
If the values in data array are in the same order as they are in the form then you can do this
insert_data_in_form: function(data) {
var formElems = $("#dataform input[type='text']");
formElems.each(function(i,elem) {
$(this).val(data[i]);
// or even better use the following faster way
// if they are always text boxes
// this.value = data[i];
});
}
Demo: http://jsfiddle.net/joycse06/AJhEW/
UPDATE (Alternate Way):
You can also achieve this using Implicit Looping with this .val(function(index,val) variant of the .val() function like this
var insert_data_in_form = function(data) {
var formElems = $("#dataform input[type='text']");
formElems.val(function(i) {
return data[i];
});
};
Demo: http://jsfiddle.net/joycse06/AJhEW/2/
el -> arr:
form_arr[form_el.attr('name')] = form_el.val();
arr -> el:
form_el.val(form_arr[form_el.attr('name')]);
Related
I want to get and store id from idArray to use each id indvidual
I tried to store in session storage but it return the last element
success: function (data) {
const myText = "";
const addressArray = [];
const titleArray = [];
const typeArray = [];
const idArray = [];
data.map((user) => {
addressArray.push(user.address);
titleArray.push(user.title);
typeArray.push(user.jtype);
idArray.push(user.id);
});
container.innerHTML = "";
for (let i = 0; i <= 3; i++) {
let clone = row.cloneNode(true);
container.appendChild(clone);
container.firstChild.innerHTML = "";
jobtitle.innerHTML = data[i].title;
jbtype.innerHTML= typeArray[i];
jbaddress.innerHTML= addressArray[i];
sessionStorage.setItem('jobid',idArray[i]);
}
}
The issue I can see is , since the key is always same , it is overriding the value of the same key.
You can instead do something like
sessionStorage.setItem("jobid-"+i,idArray[i]);
This should solve the problem for sure.
It returns the last value because you are using the same key to store each value. Try using a different key for each or alternately, create an array of ids using map function and store the array in session with the key 'jobid'.
You can serialize and store it in session as follows:
sessionStorage.setItem('jobid', JSON.stringify(idArray));
To read the same back out you can use code like
JSON.parse(sessionStorage.getItem('jobid'));
I'm trying to save multiple inputs to localStorage. I used a 'for' loop for this purpose, but it saved the same value for all three inputs. I want the separate foreach values, not all of them at once:
<script>
document.addEventListener('DOMContentLoaded', function() {
var j = document.getElementsByName('emploi').length;
var i;
for(i=0; i<=j; i++) {
var x = document.getElementsByName('emploi')[i];
x.value = localStorage['emploi'];
x.onchange = function() {
localStorage['emploi'] = this.value;
}
}
});
</script>
<!--Html-->
<!--SALE-->
<input type="text" name='emploi' placeholder='Sale'>
<!--les prof-->
<input type="text" name='emploi' placeholder='Professeur'>
<!--les classes-->
<input type="text" name='emploi' placeholder='Class'>
Store a JSON.stringified object instead of a simple string value otherwise you are using the same value for all 3
document.addEventListener('DOMContentLoaded', function() {
// parse stored JSON if it exists otherwise an empty object
var values = JSON.parse(localStorage.getItem('emploi') || '{}');
var inputs = document.getElementsByName('emploi');
for (let i = 0; i < inputs.length; i++) {
var x = inputs[i];
x.value = values[i] || '';// stored value if it exists or empty string
x.onchange = function() {
// assign value to the object above
values[i] = this.value;
// store updated version of object
localStorage.setItem('emploi', JSON.stringify(values));
}
}
});
It seems that your main issue is knowing how to save data to localStorage. You need to rewrite your code based on the syntax below.
Syntax for SAVING data to localStorage:
localStorage.setItem("key", "value");
Syntax for READING data from localStorage:
const lastname = localStorage.getItem("key");
Syntax for REMOVING data from localStorage:
localStorage.removeItem("key");
I am trying to search, find and fetch some data from a CSV file using HTML/PHP/Javascript.
I want to make a form with 2 dropdowns, one for the FROM Zone name and one for the TO Zone name, and use the Zone codes (102, 104, 105 etc) as values for the dropdown items.
After the user have selected the FROM and TO i want to display the single digit to the far right (col 5).
Example: User choose "Zone1" to "Zone4", then the number "4" should be returned.
FromZoneCode;FromZoneName;ToZoneCode;ToZoneName;Distance;;;;
101;zone1;101;zone1;1;;;;
101;zone1;104;zone4;4;;;;
101;zone1;105;zone5;5;;;;
104;zone4;101;zone1;4;;;;
104;zone4;105;zone5;2;;;;
104;zone4;104;zone4;1;;;;
I have tried to search for a solution for this but i cant seem to find the right info.
Worked out after a long time:
Don't know how you got the CSV data. In the following example, I got it by an ajax request.
No jQuery needed.
Created the dropdowns dynamically.
Set the variable delimeter to ; (or) , as required, because most CSV files contains CSV delimeter.
Give the names of the columns for which dropdowns to be created in the variables dropdownname1 and dropdownname2.
Give the name of the column to be displayed as result on chaning dropdowns in the variable resultname.
Create a <span> element with id="result" in the HTML to display the result.
Variable keys contains column names.
Variable values contains array of arrays as values.
var data = [];
$.ajax({
url:"/Users/Default/Downloads/test.csv",
type:"GET",
datatype:"csv",
success:function(response){
data = response.split(/\r\n/);
start();
}
});
//Logic starts here
//Initializations
var keys = [], values = [], delimiter = ";";
var dropdownname1 = "FromZoneName", dropdownname2 = "ToZoneName", resultname = "Distance";
var resultelem = document.getElementById("result");
//Functionalities
function createDropdown(field)
{
function createOption(option, isselected)
{
var optionelem = document.createElement("option");
optionelem.value=option;
optionelem.text=option;
optionelem.selected = isselected;
return optionelem;
}
var selectelem = document.createElement("select");
selectelem.setAttribute("id",field);
var insertedoptions = [];
for(var i=0;i<values.length;i++)
{
var option = values[i][keys.indexOf(field)];
if(insertedoptions.indexOf(option) == -1)
{
insertedoptions.push(option);
selectelem.appendChild(createOption(option));
}
}
selectelem.appendChild(createOption("",true));
return selectelem;
}
function start()
{
keys = data.splice(0,1)[0].split(delimiter);
values = [];
for(var i=0,n=data.length;i<n;i++)
{
values.push(data[i].split(delimiter));
}
var bodyelem = document.getElementsByTagName("body")[0];
bodyelem.appendChild(createDropdown(dropdownname1));
bodyelem.appendChild(createDropdown(dropdownname2));
document.getElementById(dropdownname1).addEventListener("change",displayData);
document.getElementById(dropdownname2).addEventListener("change",displayData);
}
function displayData()
{
var selectelem1 = document.getElementById(dropdownname1), selectelem2 = document.getElementById(dropdownname2);
var selectedvalue1 = selectelem1.value, selectedvalue2 = selectelem2.value;
for(var i=0,n=values.length;i<n;i++)
{
if(values[i][keys.indexOf(dropdownname1)] == selectedvalue1 && values[i][keys.indexOf(dropdownname2)] == selectedvalue2)
{
resultelem.innerHTML=values[i][keys.indexOf(resultname)];
break;
}
else
{
resultelem.innerHTML="";
}
}
}
I am using dexie.js, which is an indexDB wrapper. Anywhoo, I have an array that is called from the user's local storage, and my function is supposed to iterate through every list item in the DB and show it. However, upon clicking on my Butane it only shows the most recent input of name.
Note: You can see the entire database by adding a few values in and checking your local storage.
My JsFiddle:
https://jsfiddle.net/enzp3zws/1/
my html:
<ul id="mane"></ul>
my js:
var db = new Dexie("TestDatabase");
db.version(1).stores({
friends: '++id, name, age'
});
var collection = db.friends;
var placement = document.getElementById('rainman');
var jacement = document.getElementById('rainboy');
var stacement = document.getElementById('mane');
var listed = document.createElement('li');
function addrain(){
collection.each(function(friend){
var element = [friend.name];
for (var i = 0; i < element.length; i++){
listed.textContent = element[i];
document.getElementById('mane').appendChild(listed);
//alert(element); <-- this call alerts all names in database.
}
});
}
Please excuse the randomness of some of these variable names. I don't know what sleep is anymore.
You need to create a new 'li' element each time:
//Remove var listed = ... line in header, then:
function addrain(){
collection.each(function(friend){
var element = [friend.name];
for (var i = 0; i < element.length; i++){
var listed = document.createElement('li');
listed.textContent = element[i];
document.getElementById('mane').appendChild(listed);
}
//alert(element); <-- this call alerts all names in database.
});
}
The reason your code did not work before is that you only created one li element, and repeatedly changed its text and re-inserted it at different locations.
i am trying to use jQuery.data() and save an Object to my HTML-Elements. Everytime i add an list-Element to my unordered List it only saves the last object to the specific li-Element. Every other li-Elements saved data gets thrown away!
I've built a little Example. JSBin-Example
On the left, i create a List with an Object saved to it. On the right i am trying to show the data related to the Object.
Why does it only show the Object related to the last HTML-Element?
Working example:
JSBin-Example
That's because you are modifying innerHTML property of the wrapper element. What happens is in each iteration the elements are regenerated, the current elements are removed and the new elements don't have any stored data. Using innerHTML property is the worst way of modifying element contents. You just need to create a li element and append it to the wrapper element:
var random = 0;
// var testObject = [];
function addNewItem(){
random += 1;
var id = "testId" + random;
var text = "This is my " + random + ". text";
var data = {id: id, text: text};
// testObject.push(data);
// You can pass an object as the second argument
// to jQuery constructor and it calls the
// corresponding methods as setter
$('<li></li>', {
text: text + JSON.stringify(data),
id: id,
data: data
}).appendTo('#listId');
}
// bind and trigger click event
$("#add").on('click', addNewItem).click();
I changed
for(var i = 0; i < testObject.length; i++){
var listItem = "";
var id = testObject[i].id;
listItem += liStart + id + liStart2;
listItem += testObject[i].text;
listItem += liEnd;
unorderedList.innerHTML += listItem;
$("#"+id).data(testObject[i]);
}
to this in your updatelist function
//for(var i = 0; i < testObject.length; i++){
var id = testObject[testObject.length-1].id;
listItems += liStart + id+"savedData" + liStart2;
listItems += JSON.stringify($("#"+id).data());
listItems += liEnd;
//}
savedData.innerHTML += listItems;
and it fixed the issue
To help you understand my comment on the question I thought it best I'd give an example of what I meant.
I didn't have enough time to fully go through the solution but wanted to give an example of what I'd call more readable code.
I've added all variables at the top of the function. This will allow you to read and find items much quicker if you needed to alter them.
I've also merged a lot of the string values that you had into an object, namely the li element.
I've never used $.data() as an object before so wasn't really aware how I could use it to set the values in the updateSavedData() $('li'), although the console.log() does show the correct key / values.
$(document).ready(function(){
var uID = 0;
var testObject = [];
var unorderedList = $("#listId");
var savedList = $("#savedData");
var TOL = 0; //TestObjectLength
var textTemplate = "This is my [0] text!";
function addNewItem(){
uID++;
testObject.push({id: uID, text: textTemplate.replace("[0]", uID)});
TOL = testObject.length-1;
updateList();
}
function updateList(){
var li = $('<li>', { id: testObject[TOL].id, data: testObject[TOL], text: testObject[TOL].text });
li.appendTo(unorderedList);
updateSavedData(li.data());
}
function updateSavedData(li){
console.log(JSON.stringify(li));
$('<li>', JSON.stringify(li)).appendTo(savedList);
}
addNewItem();
$("#add").on('click', addNewItem);
});
Working Example
http://jsbin.com/ralizazahe/1/edit?js,console,output
Anyone that wants to progress on that please do as I'd also like to see how this could be progressed more.
Update
Taken it a step more and refactored to this
$(document).ready(function(){
var $displayList = $("#listId");
var $savedList = $("#savedData");
var textTemplate = "This is my {0} text!";
var uID = 0; //Unique ID
var data = { id: null, text: null }; //Gives a reference
function init(){
uID++;
data = { id: uID, text: textTemplate.replace("{0}", uID) };
}
function addNewItem(){
init();
$('<li>', data).appendTo($displayList);
updateSavedData(data);
}
function updateSavedData(li){
$('<li>', li).appendTo($savedList);
}
addNewItem();
$("#add").on('click', addNewItem);
});
http://jsbin.com/bajekagoli/1/edit?js,console,output