Javascript: creating dynamic variables and object names. / html5 localstorage - javascript

I'm working on a form that is saved by HTML5 local storage.
When pressing save:
function saveAll(){
var field1 = document.getElementById('field1').value;
localStorage.setItem('con_field1',field1);
var field2 = document.getElementById('field2').value;
localStorage.setItem('con_field2',field2);
var field3 = document.getElementById('field3').value;
localStorage.setItem('con_field3',field3);
var field4 = document.getElementById('field4').value;
localStorage.setItem('con_field4',field4);
var field5 = document.getElementById('field5').value;
localStorage.setItem('con_field5',field5);
var field6 = document.getElementById('field6').value;
localStorage.setItem('con_field6',field6);
}
And when loading the page (fills out the forms):
function ShowAll() {
var field1 = localStorage.getItem('con_field1');
document.conditioning.field1.value = field1;
var field2 = localStorage.getItem('con_field2');
document.conditioning.field2.value = field2;
var field3 = localStorage.getItem('con_field3');
document.conditioning.field3.value = field3;
var field4 = localStorage.getItem('con_field4');
document.conditioning.field4.value = field4;
var field5 = localStorage.getItem('con_field5');
document.conditioning.field5.value = field5;
var field6 = localStorage.getItem('con_field6');
document.conditioning.field6.value = field6;
}
This all works fine, but I want to re-write this in a more fancy and efficient way. I was thinking of something like this:
function ShowAll() {
var field = [];
for (i=0; i<6; i++) {
field[i] = localStorage.getItem(window['con_field' + i]);
document.purpose.field[i].value = window['con_field' + i]
}
}
But the browser is not enjoying this. Basically I need to create a loop that automatically changes the "field" name in to 'field1, field2, field3' etc. The window thing is working, but I'm just using it wrong.
Anyone has an idea?
Thanks a lot!

function showAll(t1,c1,d1) {
var field1 = localStorage.getItem('con_field1');
console.log(field1)
var field2 = localStorage.getItem('con_field2');
var field3 = localStorage.getItem('con_field3');
}

You should add all of your data to one object, stringify it, then add that to local storage under a single key.
When you load it, grab the one local storage item, parse it, then access the properties on the object.
e.g.
var save = function () {
var data = {
foo: 'bar'
};
localStorage.setItem('myData', JSON.stringify(data));
};
var load = function () {
var data = JSON.parse(localStorage.getItem('myData'));
var someProp = data.foo; // gives you 'bar'
};

It looks like your main problem is that the fields are indexed beginning with 1, but your loop indexes from 0.
What about this?
var field = [];
for (i = 1; i <= 6; i++)
{
field[i] = localStorage.getItem(window['con_field' + i]);
document.purpose.field[i].value = window['con_field' + i]
}
Also, I'm not 100% on this, but I think using document.getElementByID is more cross-browser compatible than using bracket notation on the window object, but it's been a while since I wrote plain vanilla JS, so don't quote me.

I would try document.purpose["field" + i].value = window['con_field' + i].

Related

javascript 'object object' from localstorage

I am getting an alert saying [object] object when I execute showlogsf function
var fdata = {fidval, fweightval, feggslaidval, fgraineatenval, fwaterval};
var fidval = document.getElementById('#fid');
var fweightval = document.getElementById('#fweight');
var feggslaidval = document.getElementById('#feggslaid');
var fgraineatenval = document.getElementById('#fgraineaten');
var fwaterval = document.getElementById('#fwater');
These are the two functions that could be triggered from button click
$('#submitf').click(function (){
localStorage.setItem ("fdatak", JSON.stringify(fdata));
});
$('#showlogsf').click(function(){
var fdataload = JSON.parse(localStorage.getItem("fdatak"));
alert(fdataload);
});
});
You're pushing an object as an alert. the HTML displays this as [object Object]. You have to address the actual properties of this object, so:
$('#showlogsf').click(function(){
var fdataload = JSON.parse(localStorage.getItem("fdatak"));
alert(fdataload.fidval);
alert(fdataload.fweightval);
alert(fdataload.feggslaidval);
// etc etc...
});
EDIT: Seems like you're also saving the document element, rather than the value. I assume the fdataload.properties are actual values, you should either grab the raw HTML data or input value of this instead of the HTML element itself
I guess your fdata is an array right?.
Try this var fdata = [fidval, fweightval, feggslaidval, fgraineatenval, fwaterval];
I edited values of array as xxx.value instead of xxx
var fdata = new Array();
$('#submitf').click(function (){
var fidval = document.getElementById('fid');
var fweightval = document.getElementById('fweight');
var feggslaidval = document.getElementById('feggslaid');
var fgraineatenval = document.getElementById('fgraineaten');
var fwaterval = document.getElementById('fwater');
var fdata = [];
like this
fdata.push (fidval.value, fweightval.value, feggslaidval.value, fgraineatenval.value, fwaterval.value);
localStorage.setItem ("fdata", JSON.stringify(fdata));
});
$('#showlogsf').click(function(){
var fdataload = JSON.parse(localStorage.getItem('fdata'));
document.getElementById("flogview").innerHTML = fdataload;
});
Now it saves but I have another problem, why it is replacing data every time I click showlogsf button??

Cookie is overwriiting issue

I have following code I use Jquery cookie plugin to set cookie.I need to store multiple values to a a cookie variable using jquery but every time its overwrite so multiple value doesn't store.please have a look into my code and help me.I have a select box and its name is inserted into a cookie variable every time.
$(".cookieul").on("click",function(){
var a ='';
var myCookies = [];
var newValue = $(".client option:selected").text();
a += newValue;
myCookies.push(a);
$.cookie("example", JSON.stringify(myCookies), { expires: 7 });
});
You may write like this -
$(".cookieul").on("click",function(){
var newValue = $(".client option:selected").text();// your new selected text
var old_value_json = $.cookie("example"); // check your plugin get cookie syntax
var old_value_arr = [];
old_value_arr = $.parseJSON(old_value_json); //converting your stored JSON string to javascript array
old_value_arr.push(newValue ); // pushing new value to array
$.cookie("example", JSON.stringify(old_value_arr ), { expires: 7 });//setting new value to cookie
});
This solves the issue.Any other better way
var myCookies = [];
$(".cookieul").on("click",function(){
var newValue = $(".client option:selected").text();
var old_value_json = $.cookie("example");
myCookies = $.parseJSON(old_value_json)
myCookies.push(newValue);
$.cookie("example", JSON.stringify(myCookies), { expires: 7 });
var storedAry = JSON.parse($.cookie('example'));
console.log(unique(storedAry));
function unique(list) {
var result = [];
$.each(list, function(i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});
return result;
}
});

Can I create a reference to a variable in javascript?

I tried the following:
$scope.qs = {};
$scope.qh = {};
$scope.qv = {};
var qs = $scope.qs;
var qh = $scope.qh;
var qv = $scope.qv;
$scope.getQuestionHeaders = function () {
var url = '/api/Test/GetQuestionHeaders?id=1';
$http.get(url)
.success(function (data, status, headers, config) {
qh = data.testQuestionHeaders;
qs = qh[0];
My data is assigned to qs and I can see additional fields such as qs.i, qs.q etc. But when I use the chrome developer tools I notice that nothing has been assigned to $scope.qs
That's correct.
You're essentially doing:
foo.someProp = 1;
var bar = foo.someProp;
bar = 3;
Would you expect foo.someProp to be 3? If you want to update the $scope.qs reference, then you need to do it directly, otherwise you're just changing a local variable reference. You can modify items inside qs:
qs.foo = 1;
console.log($scope.qs.foo);
You are overriding the variables qh and qs, so they loose their previous references. You have to do this if you want to keep both vars synchronized :
$scope.qh = qh = data.testQuestionHeaders;
$scope.qs = qs = qh[0];
Updating properties doesn't affect variables references :
qh.witness = true;
$scope.qh.witness === qh.witness === true; // true

how can i access a variable in one javascript in another javascript?

Hi guys This is my code of two javascript.i want to access variable defined in first javascript into another script.
1)
<script>
$(document).ready(function()
{
$('pre.codeguru').each(function()
{
var pre = this;
var form = $('form[name=sample]').clone();
$(form).removeAttr('name');
$(form).removeClass('hidden');
$($(form).find('textarea')[0]).val($(pre).text());
var id = $(pre).attr('id');
$(form).find('div textarea[name=code]').first().attr('id', id);
$(pre).replaceWith(form);
});
var editors = [];
$('textarea[name=codeguru]').each(function()
{
var editor = CodeMirror.fromTextArea(this,
{
lineNumbers: true,
matchBrackets: true,
mode: "application/x-httpd-perl",
tabMode: "shift"
});
editors.push(editor);
});
});
</script>
2)
<script type="text/javascript">
function execute() {
p5pkg.CORE.print = function(List__) {
var i;
for (i = 0; i < List__.length; i++) {
document.getElementById('print-result').value += p5str(List__[i])
}
return true;
};
p5pkg["main"]["v_^O"] = "browser";
p5pkg["main"]["Hash_INC"]["Perlito5/strict.pm"] = "Perlito5/strict.pm";
p5pkg["main"]["Hash_INC"]["Perlito5/warnings.pm"] = "Perlito5/warnings.pm";
var source = editor.getValue();
alert(source);
var pos = 0;
var ast;
var match;
document.getElementById('print-result').value = "";
try {
var start = new Date().getTime();
var js_source = p5pkg["Perlito5"].compile_p5_to_js([source]);
var end = new Date().getTime();
var time = end - start;
// run
start = new Date().getTime();
eval(js_source);
end = new Date().getTime();
time = end - start;
}
catch(err) {
//document.getElementById('log-result').value += "Error:\n";
}
}
</script>
Now my problem is i want to access the editor defined in first javascript as
var editors = [];
$('textarea[name=codeguru]').each(function()
{
var editor = CodeMirror.fromTextArea(this,
{
lineNumbers: true,
matchBrackets: true,
mode: "application/x-httpd-perl",
tabMode: "shift"
});
editors.push(editor);
});
in second javascript.
anyone has answer of this then please help me to do so
If you leave out var while defining variables they will be globally accessible.
So
pre = this;
instead of
var pre = this;
would make pre accessible from every function.
the only way I can think is to pass the variable into the other functions as a variable
function otherJavaFile.myFunction (myVariable);
or alter a variable in the HTML i.e. the custom data-value and then the other script can access it. I don't like global variables.
// Sheet 1
$("#myDiv").attr("data-variable",yourValue);
// Sheet 2
var secondVariable = $("#myDiv").attr("data-variable");
buddy i am not comfortable with jquery...
I hope you are looking forward for the iframes/frames on same document[window sharing].
Based on my knowledge of Javascript DOM to access a variable defined in one document inside another document.You have to use document.importNode(original Node as in other document,boolean) method as per DOM 2.
Do something like this for javacript code ...
documentI(original variable/node present here)- iframe.contentDocument.getElementsByTagName(/Tag name of Node/)...
documentII(node to be cloned here)-
document.importNode(originalNode,True)
I hope this works

Generating JSON Object

I'm trying to parse the rows in a table that I generate using Javascript by adding items to a cart and then create a json object when the user hits save order of all the items and pass it to a php script using $.post in jQuery.
The only trouble I'm having is understanding JSON objects and how to push more items onto the object. I get an error in firebug telling me that devices[i] is undefined. Not really sure how else to accomplish this. I thought it was really just an array.
function Save()
{
var devices = new Object();
var i = 0;
$("#device_tbl tr:gt(0)").each(function(){
var manufid = $(this).find("td").eq(0).find(".manuf_id").html();
var modelid = $(this).find("td").eq(1).find(".model_id").html();
var condition = $(this).find("td").eq(2).find("select").val();
var carrier = $(this).find("td").eq(3).find("select").val();
var imei = $(this).find("td").eq(4).find("input").val();
var price = $(this).find("td").eq(5).html();
alert(manufid+"\n"+modelid+"\n"+carrier+"\n"+imei+"\n"+price);
devices[i].manufid = manufid;
devices[i].modelid = modelid;
devices[i].carrier = carrier;
devices[i].imei = imei;
devices[i].price = price;
i++;
});
document.write(devices); //just for debugging
$("#final").show();
}
You currently have devices declared as an object, but you're treating it like an array.
You need to declare it as an array of objects.
function Save()
{
var devices = new Array();
var i = 0;
$("#device_tbl tr:gt(0)").each(function(){
var manufid = $(this).find("td").eq(0).find(".manuf_id").html();
var modelid = $(this).find("td").eq(1).find(".model_id").html();
var condition = $(this).find("td").eq(2).find("select").val();
var carrier = $(this).find("td").eq(3).find("select").val();
var imei = $(this).find("td").eq(4).find("input").val();
var price = $(this).find("td").eq(5).html();
alert(manufid+"\n"+modelid+"\n"+carrier+"\n"+imei+"\n"+price);
devices[i] = new Object();
devices[i].manufid = manufid;
devices[i].modelid = modelid;
devices[i].carrier = carrier;
devices[i].imei = imei;
devices[i].price = price;
i++;
});
document.write(devices); //just for debugging
$("#final").show();
}
or something like that.
(Updated to show it in your code)

Categories

Resources