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");
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 can make variables one by one like this:
var bookName = document.getElementById('bookName').value,
author = document.getElementById('author').value,
translator = document.getElementById('translator').value,
pageCount = document.getElementById('pageCount').value,
publisher = document.getElementById('publisher').value,
isbn = document.getElementById('isbn').value,
printingYear = document.getElementById('printingYear').value;
But it's so hard to write and it doesn't fit with the DRY rule. So I changed the code to this:
function variableMaker(argument) {
var tags = document.getElementsByTagName(argument);
for (var i = 0; i < tags.length; i++) {
var tags[i].name = tags[i].value;
}
}
variableMaker(input);
But I can't understand if it is the true way or if it is working? How do I check if it's true or not?
In this code, I tried to get the computer find all the input tags and make variables with their name property and assign it to its values for each of them.
If I understand correctly then you want to gather data from all <input> elements. If so, then you need to call it like this:
variableMaker('input'); // use quotes!
Still even then your function does not return anything, it just ends.
You'd also better create your own object for the return collection, instead of adding values to an existing object.
Here is a working solution:
function variableMaker(tagName) {
var elements = document.getElementsByTagName(tagName);
var items = {};
for (var i = 0; i < elements.length; i++) {
var elem = elements[i];
items[elem.id] = elem.value; // Use id as key, each points to the corresponding value.
}
return items;
}
var values = variableMaker('input');
console.log(values); // show the entire return object
console.log(values.author); // access individual items from the return object
console.log(values.isbn);
<input type="text" id="author" value="Dahl">
<input type="text" id="isbn" value="1234">
.
i have a simple code of javascript which displays text from url.
example: index.html?id=001
then its output displays in html page as 001. but i want that data (id=001) into html text box which display only "001" into textbox.
here is my code.
<script type="text/javascript">
function GET() {
var data = [];
for(x = 0; x < arguments.length; ++x)
data.push(location.href.match(new RegExp("/\?".concat(arguments[x],"=","([^\n&]*)")))[1])
return data;
}
</script>
<br />
<script type="text/javascript"> document.write(GET("id")[0]); </script>
<br /><br />
<input type="text" id="" value="" name="" />
Actually i want that "001" into textbox as a textbox value.
Put the script after the input then just set its value:
<input type="text" id="myInput" value="" name="" />
<script type="text/javascript">
function GET() {
var data = [];
for(x = 0; x < arguments.length; ++x)
data.push(location.href.match(new RegExp("(/\?id=)([^\&]*)"))[2]);
return data;
}
document.getElementById('myInput').value = (GET("id")[0]);
</script>
Regular expressions are probably overkill for this, and your expression will only find the querystring value if it immediately follows the ?.
You should use location.search rather than the full URL, because then you just need to take everything after the first character (which will be ? if there is anything), and it will eliminate hashes.
I used simple string splitting to create a reusable map of key/value pairs for lookup.
function GET() {
var data = [];
for (var i = 0; i < arguments.length; i++) {
data.push(getQueryMap()[arguments[i]]);
}
return data;
}
var queryMap = null;
function getQueryMap() {
if (queryMap) { return queryMap; }
queryMap = {};
var querySplit = location.search.substring(1).split('&');
for (var i = 0; i < querySplit.length; i++) {
var thisQuery = querySplit[i].split('=', 2);
queryMap[thisQuery[0]] = thisQuery[1];
}
return queryMap;
}
To use the input and get the value into it, you need an ID on it or another way to identify it:
<input type="text" id="someInput" value="" name="" />
Then, after it, put a script like so:
<script type="text/javascript">
document.getElementById('someInput').value = GET('id')[0];
</script>
Replace...
<script type="text/javascript"> document.write(GET("id")[0]); </script>
with...
<script type="text/javascript">$('input').val(GET("id")[0]);</script>
Place that line after the input box.
Here are a couple of functions that help you parse a URL's parameters into an associative array.
function transformToAssocArray(prmstr) {
var arr = {};
var prmarr = prmstr.split("&");
for (var i = 0; i < prmarr.length; i++) {
var tmparr = prmarr[i].split("=");
arr[tmparr[0]] = tmparr[1];
}
return arr;
}
function getURLParmeters() {
var prmstr = window.location.search.substr(1);
if (prmstr === null || prmstr === '' ) {
return null;
}
return transformToAssocArray(prmstr);
}
Then you can assign all URL parameters to a variable like this:
var params = getURLParameters();
From then on, you can access the parameter's value by referencing params.paramternamehere. So, to assign the value of the "id" parameter to a text input, just grab that input element and assign params.id to that input's value.
var inputElement = document.getElementById("myTextInput");
if (params !== null) {
inputElement.value = params.id;
}
This technique utilizes the HTMLHyperlinkElementUtils.search property to reliably separate URL location components from paramters, and then does a simple string split to separate key-value pairs and then store those pairs in an associative array.
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')]);
I have a form
<form>
<input type="text" name="Name" />
<input type="checkbox" name="Feature.Translate" />
<input type="checkbox" name="Feature.Share" />
<input type="submit" value="Convert into an object" />
</form>
I want to convert it in an object
{
Name: "John Connor's Terminator",
Feature:
{
Translate: true // if checked
// Share wasn't checked
}
}
How can I map the form to an object that has this tree structure?
Add this method to help you build the tree
// add keys to an object as a tree
// ["a", "b", "c"] will generate
// a { b: { c: def } }
// def is the value of the leaf node
var AddToTree = function(obj, keys, def)
{
for (var i = 0, length = keys.length; i < length; ++i)
obj = obj[keys[i]] = i == length - 1 ? def : obj[keys[i]] || {};
};
Create a function for a jQuery selector that will convert the form in an object
$.fn.serializeObject = function()
{
var o = {}; // final object
var a = this.serializeArray(); // retrieves an array of all form values as
// objects { name: "", value: "" }
$.each(a, function() {
var ns = this.name.split("."); // split name to get namespace
AddToTree(o, ns, this.value); // creates a tree structure
// with values in the namespace
});
return o;
};
With these two functions define you can set an event on the submit button:
$(":submit").click(function(e){
// contains the object from the form
// respecting element namespaces
var obj = $("form").serializeObject();
});
Something like the following should work:
function serializeData() {
//this is where we'll store our serialized data
var serializedData = {};
//iterate over input, select, and textarea elements
jQuery("input, select, textarea").each(function(index) {
var $element = jQuery(this);
var name = $element.attr("name");
//we only want to serialize the element if it has a 'name' attribute
if(typeof name != "undefined") {
//split on the . to get an array
var parts = name.split(/\./);
//start building the serialized data
var currentPart = serializedData;
for(var i = 0; i < parts.length; i++) {
//if this particular element doesn't already exist in our hash, create it
//and initialize it to an empty hash
if(typeof serializedData[parts[i]] == "undefined") {
currentPart[parts[i]] = {};
}
//if we're currently looking at the very last element in the array then
//it means that we need to set its value to the value of the corresponding
//input element. Otherwise, it means that there are still keys within the
//array and so we set `currentPart` to the new hash that we just created
if(i == parts.length - 1) {
//if the element is a checkbox or a radio, we need to see if it's checked
//instead of looking at its value
if($element.attr("type").toLowerCase() == "checkbox" || $element.attr("type").toLowerCase() == "radio") {
currentPart[parts[i]] = $element.is(":checked");
}
else {
currentPart[parts[i]] = $element.val();
}
}
else {
currentPart = currentPart[parts[i]];
}
}
}
});
console.log(serializedData);
}
Check out the fiddle.
All you need to do now is to bind serializeData to the submit event on the form.