Parsing JavaScript, inside HTML - javascript
I have this Script tag inside an HTML and I need to parse for instance to get all the data inside the new String(). Is there a way to parse this data?
Does REGEX have to be used here or is there a more efficient way to do this?
<script language="JavaScript1.1">
function X(n) {
arrayindex = n;
s=new String(dataArray[arrayindex]);
a=s.split(",");
dateheading="Date:";
if (arrayindex < 0) {
document.dform.dinput.value="";
} else {
if (arrayindex == 0) {
document.dform.dinput.value=dateheading + a[0] + " O=" + a[1] + " H=" + a[2] + " L=" + a[3] + " C=" + a[4];
} else {
document.dform.dinput.value=dateheading + a[0] + " O=" + a[1] + " H=" + a[2] + " L=" + a[3] + " C=" + a[4];
}
}
}
var dataStr = new String('11/27/18 07:40,1.1322,1.13228,1.132,1.13212|11/27/18 07:35,1.13192,1.1322,1.13192,1.13203|11/27/18 07:30,1.1318,1.13202,1.1318,1.1319|11/27/18 07:25,1.13165,1.13191,1.13165,1.13188|11/27/18 07:20,1.1317,1.13174,1.13143,1.13143|11/27/18 07:15,1.13182,1.13192,1.1316,1.13177|11/27/18 07:10,1.13208,1.13213,1.1319,1.13213|11/27/18 07:05,1.1319,1.1321,1.13176,1.1321|11/27/18 07:00,1.13196,1.1321,1.13196,1.132|11/27/18 06:55,1.13232,1.13232,1.13187,1.13187|11/27/18 06:50,1.1319,1.13234,1.1319,1.1323|11/27/18 06:45,1.13216,1.13217,1.1319,1.132|11/27/18 06:40,1.13188,1.13198,1.13184,1.13198|11/27/18 06:35,1.13222,1.13222,1.132,1.13208|11/27/18 06:30,1.1318,1.1323,1.1318,1.1323|11/27/18 06:25,1.13178,1.1321,1.13178,1.13191|11/27/18 06:20,1.13184,1.13184,1.13162,1.13162|11/27/18 06:15,1.1316,1.13179,1.1316,1.13179|11/27/18 06:10,1.13194,1.132,1.1315,1.1318|11/27/18 06:05,1.1319,1.13225,1.1319,1.13191|11/27/18 06:00,1.13169,1.13174,1.1316,1.13169|11/27/18 05:55,1.1312,1.13166,1.1312,1.13166|11/27/18 05:50,1.13101,1.13127,1.131,1.13122|11/27/18 05:45,1.1313,1.1313,1.13111,1.13111|11/27/18 05:40,1.1317,1.1317,1.1313,1.13141|11/27/18 05:35,1.13159,1.13159,1.13135,1.13142|11/27/18 05:30,1.13203,1.13203,1.1317,1.1317|11/27/18 05:25,1.13187,1.13217,1.13187,1.13208|11/27/18 05:20,1.13226,1.13226,1.13185,1.13185|11/27/18 05:15,1.13151,1.13163,1.13151,1.13163|11/27/18 05:10,1.13141,1.13149,1.1313,1.13149|11/27/18 05:05,1.13153,1.13153,1.13128,1.1314|11/27/18 05:00,1.13114,1.13148,1.13114,1.13148|11/27/18 04:55,1.13149,1.13149,1.13106,1.13106|11/27/18 04:50,1.13212,1.13219,1.13203,1.13203|11/27/18 04:45,1.13232,1.13244,1.13209,1.13209|11/27/18 04:40,1.13225,1.13244,1.13223,1.13223|11/27/18 04:35,1.13233,1.13233,1.13217,1.13223|11/27/18 04:30,1.1322,1.13222,1.13206,1.1321|11/27/18 04:25,1.13174,1.13227,1.13174,1.13227|11/27/18 04:20,1.1316,1.13174,1.1315,1.13174|11/27/18 04:15,1.13181,1.13181,1.1314,1.13163|11/27/18 04:10,1.1319,1.13212,1.1319,1.13191|11/27/18 04:05,1.1317,1.13206,1.1317,1.13206|11/27/18 04:00,1.1311,1.13153,1.1311,1.13142|11/27/18 03:55,1.1313,1.1313,1.13113,1.13113|11/27/18 03:50,1.13136,1.13146,1.131,1.131|11/27/18 03:45,1.13147,1.13164,1.13145,1.13145|11/27/18 03:40,1.13091,1.13164,1.13091,1.13158|11/27/18 03:35,1.13109,1.13123,1.13106,1.1311|11/27/18 03:30,1.1308,1.13135,1.1308,1.13117|11/27/18 03:25,1.13115,1.13121,1.1309,1.1309|11/27/18 03:20,1.13089,1.13105,1.13082,1.13105|11/27/18 03:15,1.13076,1.13085,1.1304,1.13085|11/27/18 03:10,1.13072,1.13075,1.1304,1.13069|11/27/18 03:05,1.13111,1.13111,1.1309,1.13107|11/27/18 03:00,1.131,1.13151,1.13073,1.13073|11/27/18 02:55,1.13201,1.13201,1.1311,1.13122|11/27/18 02:50,1.13209,1.13226,1.1318,1.13218|11/27/18 02:45,1.13202,1.13229,1.13202,1.13209|11/27/18 02:40,1.13293,1.13293,1.1321,1.13215|11/27/18 02:35,1.13262,1.13311,1.13257,1.13257|11/27/18 02:30,1.13191,1.13389,1.13191,1.13353|11/27/18 02:25,1.1321,1.1321,1.13159,1.13164|11/27/18 02:20,1.13302,1.13302,1.13263,1.13263|11/27/18 02:15,1.1328,1.13304,1.13269,1.13304|11/27/18 02:10,1.13341,1.13359,1.1331,1.1331|11/27/18 02:05,1.13312,1.13328,1.13312,1.13325|11/27/18 02:00,1.13286,1.13308,1.13286,1.13308|11/27/18 01:55,1.13255,1.1328,1.1324,1.1327|11/27/18 01:50,1.13279,1.13297,1.13263,1.13263|11/27/18 01:45,1.1331,1.1331,1.13265,1.13266|');
dataArray = dataStr.split("|");
dataStr = null;
dataLength = dataArray.length;
</script>
Summary: How to extract 11/27/18 07:40,1.1322,1.13228,1.132,1.1321...
You can do this easily with regex:
test_js = "new String('x|y|z')"
string = re.search(r"new String\('(.*)'\)", test_js)[1]
# 'x|y|z'
parts = string.split('|')
# ['x', 'y', 'z']
Related
How to decode Javascript _0x Hex
I tried to decode this code but I did not succeed: var _0x147bb5 = _0xe0c4, _0x41852d = _0xe0c4, _0x39ac2c = _0xe0c4; (function (_0x3c89e2, _0x4b3ebe) { var _0x331330 = _0xe0c4, _0x279707 = _0xe0c4, _0x50917c = _0xe0c4, _0x489044 = _0x3c89e2(); while (!![]) { try { var _0x36e386 = -parseInt(_0x331330(0x133)) / 0x1 + -parseInt(_0x279707('0x12a')) / 0x2 + -parseInt(_0x331330(0x111)) / 0x3 + -parseInt(_0x331330(0x12f)) / 0x4 + parseInt(_0x279707('0x10a')) / 0x5 * (-parseInt(_0x279707('0xf1')) / 0x6) + -parseInt(_0x331330('0x109')) / 0x7 + parseInt(_0x331330(0xee)) / 0x8 * (parseInt(_0x279707(0x11a)) / 0x9); if (_0x36e386 === _0x4b3ebe) break; else _0x489044['push'](_0x489044['shift']()); } catch (_0x108487) { _0x489044['push'](_0x489044['shift']()); } } }(_0x5a9e, 0x7f5a2)); var s = _0x147bb5('0x12b') + _0x147bb5(0xdc) + _0x39ac2c('0x118') + '91', f = 0xb, l = lf(), message = _0x39ac2c('0x117') + _0x39ac2c('0xe7') + _0x39ac2c('0x108') + _0x147bb5('0xd4') + 'ot\x20' + _0x147bb5('0x104') + _0x41852d(0xd3) + _0x39ac2c('0x122') + _0x39ac2c('0xef') + _0x41852d(0x127) + _0x41852d('0x102') + _0x41852d('0xfb') + _0x147bb5(0xe2) + _0x39ac2c(0xf2) + _0x147bb5(0xe5) + _0x41852d(0xd6) + _0x39ac2c(0x125) + _0x41852d(0xff) + _0x147bb5(0xd7) + _0x41852d('0x110') + _0x39ac2c('0x11e') + _0x39ac2c(0xdd) + _0x41852d(0x107) + 'ea)'; function rtclickcheck(_0xf37bcd) { var _0x5b07b6 = _0x39ac2c, _0x189d42 = _0x41852d, _0x158d5e = _0x147bb5; if (navigator[_0x5b07b6(0xfd) + _0x189d42(0xf5) + 'e'] == _0x158d5e('0xe4') + _0x189d42(0xde) + 'pe' && _0xf37bcd[_0x5b07b6('0xfc') + 'ch'] == 0x3) return alert(message), ![]; if (navigator[_0x5b07b6(0xfd) + _0x189d42(0xf8) + _0x5b07b6('0x11d') + 'n'][_0x5b07b6('0xec') + _0x158d5e(0x128) + 'f'](_0x158d5e(0xe6) + 'E') != -0x1 && event[_0x189d42('0x126') + _0x158d5e('0x132')] == 0x2) return alert(message), ![]; } function _0x5a9e() { var _0x521b96 = ['Thi', '7109872DszjuD', '4405xemFJj', 'deA', '//r', 'cre', 'hre', 'h=/', 're.', '1823784ZeLCWd', ';\x20p', 'etc', 'cap', 'cha', 'crt', 'Ooh', '794', 'TCS', '14494869UZdEDp', 'onm', 'erH', 'sio', 'com', 'ute', 'dli', 'men', 'py\x20', '_y=', 'tBy', 'uth', 'but', 'rot', 'exO', 'inn', '603236FmaGTN', '-11', 'exp', 'ous', 'toU', '2882436fEtPRL', 'dit', 'kie', 'ton', '1000745kgQiEE', '\x20Co', 's\x20N', 'hos', '//y', 'sto', 'len', 'pat', 'tri', '.ly', '350', '\x20(y', 'sca', 'gth', 'lin', 'rib', 'by\x20', 'Att', 'Net', 'ps:', 'MSI', '!!\x20', 'edo', 'ide', 'tna', '10;', 'ind', '/yu', '24DoydZk', '-\x20P', 'rCo', '4518TXMdnf', 'htt', 'N_f', 'Ele', 'Nam', 'and', 'get', 'Ver', 'ire', 'ati', 'ed\x20', 'whi', 'app', 'coo', 'eme', 'TML', 'ath', 'ect', 'sli', 'For', 'Tim', 'set', 'uid']; _0x5a9e = function () { return _0x521b96; }; return _0x5a9e(); } document[_0x147bb5(0x11b) + _0x147bb5('0x12d') + _0x147bb5('0xe8') + 'wn'] = rtclickcheck; if (l == s && s[_0x147bb5(0xd8) + _0x147bb5('0xdf')] == f) { var ceditf = document[_0x147bb5(0xf7) + _0x41852d(0xf4) + _0x39ac2c('0x121') + _0x147bb5(0x124) + 'Id'](_0x39ac2c(0x10d) + _0x147bb5('0x130') + _0x147bb5('0xe0') + 'k'), citf = document[_0x39ac2c(0xf7) + _0x147bb5('0xf4') + _0x39ac2c('0x121') + _0x39ac2c('0x124') + 'Id'](_0x39ac2c('0x116') + _0x39ac2c(0xe0) + 'k'); o(); var citdf = document[_0x41852d('0xf7') + _0x147bb5('0xf4') + _0x41852d(0x121) + _0x41852d('0x124') + 'Id'](_0x41852d('0x116') + _0x147bb5('0x120') + 'nk'); function checkLIC() { var _0x4072d7 = _0x41852d, _0x264ab4 = _0x41852d, _0x1a0d97 = _0x147bb5; if (cedit['inn' + _0x4072d7('0x11c') + _0x4072d7(0x100)][_0x1a0d97('0xd8') + _0x4072d7('0xdf')] === 0x0) return invalidLIC(), ![]; } } var cedit = document[_0x41852d(0xf7) + _0x39ac2c(0xf4) + _0x39ac2c(0x121) + _0x41852d('0x124') + 'Id'](_0x147bb5('0x10d') + _0x39ac2c(0x130) + _0x39ac2c(0xe0) + 'k'); function _0xe0c4(_0x488be0, _0x324154) { var _0x5a9e88 = _0x5a9e(); return _0xe0c4 = function (_0xe0c4a8, _0x3812b4) { _0xe0c4a8 = _0xe0c4a8 - 0xd3; var _0x1108f7 = _0x5a9e88[_0xe0c4a8]; return _0x1108f7; }, _0xe0c4(_0x488be0, _0x324154); } !cedit && invalidLIC(); function o() { _0x162858(); function _0x162858() { var _0x139ac8 = _0xe0c4, _0x75417f = _0xe0c4, _0x15d340 = _0xe0c4, _0x5960f5 = new Date(); _0x5960f5[_0x139ac8(0x106) + _0x75417f('0x105') + 'e'](_0x5960f5[_0x75417f(0xf7) + _0x15d340(0x105) + 'e']() + 0x15180 * 0x3); var _0x43eec0 = _0x75417f(0x12c) + _0x15d340(0xf9) + 's=' + _0x5960f5[_0x15d340('0x12e') + _0x139ac8(0x119) + _0x139ac8(0xda) + 'ng'](); document[_0x15d340('0xfe') + 'kie'] = _0x15d340(0x114) + _0x139ac8('0x123') + _0x15d340('0xeb') + _0x15d340('0xd9') + _0x75417f('0x10f') + ';', document[_0x75417f(0xfe) + _0x15d340('0x131')] = 'JSO' + _0x139ac8(0xf3) + _0x75417f('0x113') + 'h' + '=' + fetchon + ';' + _0x43eec0 + (_0x139ac8(0x112) + _0x15d340('0x101') + '=/'), window['loc' + _0x15d340(0xfa) + 'on'][_0x15d340('0x10e') + 'f'] = api; } } function invalidLIC() { } function checkLIC() { var _0x4dac69 = _0x39ac2c, _0x55bc12 = _0x41852d, _0x4c895a = _0x147bb5; if (cedit[_0x4dac69(0x129) + _0x4dac69('0x11c') + _0x4c895a(0x100)][_0x55bc12('0xd8') + _0x4dac69(0xdf)] === 0x0) return invalidLIC(), ![]; else { if (cedit[_0x4c895a('0xf7') + _0x55bc12(0xe3) + _0x55bc12(0xe1) + _0x4c895a('0x11f')](_0x4dac69(0x10e) + 'f') !== _0x4c895a(0xf2) + _0x4c895a('0xe5') + _0x55bc12('0x10c') + 'ebr' + _0x4c895a('0xf6') + _0x4c895a(0xdb) + _0x55bc12('0xed') + _0x4c895a(0xe9) + 'a/') return invalidLIC(), ![]; } } checkLIC(), setInterval( function () { checkLIC(); }, 0x1388 ); function lf() { var _0x5a8bac = _0x39ac2c, _0x505e9a = _0x147bb5, _0xd36b1d = _0x147bb5, _0x5b07b5 = location[_0x5a8bac(0xd5) + _0x505e9a('0xea') + 'me'][_0x5a8bac(0x103) + 'ce'](0x2)[_0x505e9a(0x103) + 'ce'](0x0, -0x2) + '24', _0x130606 = 0x0; if (_0x5b07b5[_0x5a8bac('0xd8') + _0xd36b1d('0xdf')] == 0x0) return _0x130606; for (i = 0x0; i < _0x5b07b5[_0x5a8bac('0xd8') + _0xd36b1d(0xdf)]; i++) { char = _0x5b07b5[_0xd36b1d('0x115') + _0xd36b1d('0xf0') + _0xd36b1d(0x10b) + 't'](i), _0x130606 = (_0x130606 << 0x5) - _0x130606 + char, _0x130606 = _0x130606 & _0x130606; } return _0x130606; } https://jsfiddle.net/utpgLw06/ So My first approach is to use online tools, but none of them works. I also try to manually decode it by calling the function name console.log(_0x331330(0x133)) but it just shows strings that I don't understand. I also tried to decode those strings by using much hex at numerical decoders but none of them works. Anyone can help me, please?
I played a bit with this code: The _Ox names are just variable names. You can make the code more readable by collecting all such distinct names and replace them with more readable names, like v1, v2, v3, .... There are two variables referenced which are not defined, api and fetchon. I suppose that the page where this script runs, has defined them somewhere. The first part of the script is harmless and just shuffles an array of strings, which is later used to obfuscate strings (often property names). You can execute it The code that needs de-obfuscation is the code that gets/sets properties of window, document, nagivator, ...and other objects. You can get a long way by putting that part of the script in a template literal, and evaluating all those expressions that evaluate to a property name, or to a value assigned to a property. Functions and immediate code are mixed. It helps to reorganise that a bit. Some functions have local variables which are constants and have unique names. These can be moved to the global scope and can often be evaluated safely, so the rest of the function's code can be clarified inside a template literal (like explained above). Any remaining variables (not evaluated), can be given more telling names by seeing how they are used. Anyway, here is the result I got to: function rtclickcheck(e) { if (navigator.appName == "Netscape" && e.which == 3) return alert("Ooh!! This Not For Copy - Protected by https://yuthemestore.com (yuidea)"), false; if (navigator.appVersion.indexOf("MSIE") != -1 && event.button == 2) return alert("Ooh!! This Not For Copy - Protected by https://yuthemestore.com (yuidea)"), false; } document.onmousedown = rtclickcheck; function o() { var date = new Date(); date.setTime(date.getTime() + 259200); var expiration = "expires=" + date.toUTCString(); document.cookie = "cap_y=10;path=/;"; // fetchon and api must be defined? document.cookie = "JSON_fetch=" + fetchon + ";" + expiration + "; path=/"; window.location.href = api; } function invalidLIC() { } function checkLIC() { if (cedit.innerHTML.length === 0) return invalidLIC(), false; else { if (cedit.getAttribute("href") !== "https://rebrand.ly/yuidea/") return invalidLIC(), false; } } function lf() { var decrypted = location.hostname.slice(2).slice(0, -2) + '24', encrypted = 0; if (decrypted.length == 0) return encrypted; for (i = 0; i < decrypted.length; i++) { char = decrypted.charCodeAt(i); encrypted = (encrypted << 5) - encrypted + char; encrypted = encrypted & encrypted; } return encrypted; } var l = lf(); var s = "-1135079491"; if (l == s && s.length == 11) { var ceditf = document.getElementById("creditlink"), citf = document.getElementById("crtlink"); o(); var citdf = document.getElementById("crtdlink"); function checkLIC() { if (cedit.innerHTML.length === 0) return invalidLIC(), false; } } var cedit = document.getElementById("creditlink"); !cedit && invalidLIC(); checkLIC(); setInterval(checkLIC, 5000); This code seems to do the following things: Avoid that the user can view the source of the page with a right click Obfuscates the current site's hostname through bitshifting and summing, and checks that the result has a certain value. I didn't try to find out what the original hostname would have to be to get a match. Sets some variables like ceditf which are not used in this script, but maybe elsewhere If the host matches, two cookies are set, and a navigation occurs (to whatever api has as URL) Every 5 seconds checks the content of the element with id "creditlink". If the contents of "creditlink" are not as expected it calls invalidLIC, but that function is empty -- I think that might have had code in a previous version of this script, but it was later removed.
JavaScript: Remove Double Quotes - JSON.Stringify()
After using he JSON.stringify() method in JavaScript to allow JSON data render in the browser it outputs double quotations " " at either end of the property rendered in the browser - any idea how to resolve this? Here is my code - <li class="divider">Brown Eyes</li> <div id="output1"></div> <li class="divider">Green Eyes</li> <div id="output2"></div> <script> var myContainer = ""; var a = new XMLHttpRequest(); a.open("GET", "https://api.myjson.com/bins/1dwnm", true); a.onreadystatechange = function () { console.log(a); if (a.readyState == 4) { var obj = JSON.parse(a.responseText); for (i = 0; i < obj.length; i++) { if (obj[i].eyeColor == 'brown') { var myContainer = "<ul class='list'><li>" + obj[i].name.first + " " + obj[i].name.last + " - " + obj[i].eyeColor + "</li></ul>"; var myContainer = JSON.stringify(myContainer); document.getElementById('output1').innerHTML += myContainer; } if (obj[i].eyeColor == 'green') { var myContainer = "<ul class='list'><li>" + obj[i].name.first + " " + obj[i].name.last + " - " + obj[i].eyeColor + "</li></ul>"; var myContainer = JSON.stringify(myContainer); document.getElementById('output2').innerHTML += myContainer; } } } } a.send(); </script>
Because "<ul class='list'><li>Faye Garrett - brown</li></ul>" is not a valid JSON string. Uncomment your stringify lines and it works.
Parsing a JSON Array with JavaScript returning selected parts
I have a very simple snipplet for a json array and a javascript function that now returns a single argument: <!DOCTYPE html> <html> <body> <h2>JSON Array Test</h2> <p id="outputid"></p> <script> var arrayinput = '{"collection":[' + '{"firstAttr":"XXXA","secAttr":"13156161","lastAttr":"01" },' + '{"firstAttr":"XXXB","secAttr":"11153325","lastAttr":"02" },' + '{"firstAttr":"XXXC","secAttr":"14431513","lastAttr":"03" },' + '{"firstAttr":"XXXC","secAttr":"161714","lastAttr":"01" },' + '{"firstAttr":"XXXC","secAttr":"151415","lastAttr":"02" },' + '{"firstAttr":"XXXC","secAttr":"114516","lastAttr":"02" },' + '{"firstAttr":"XXXC","secAttr":"131417","lastAttr":"03" },' + '{"firstAttr":"XXXC","secAttr":"1311865","lastAttr":"03" },' + '{"firstAttr":"XXXC","secAttr":"1314153","lastAttr":"01" },' + '{"firstAttr":"XXXC","secAttr":"13312163","lastAttr":"01" }]}'; obj = JSON.parse(arrayinput); document.getElementById("outputid").innerHTML = obj.collection[1].firstAttr + " " + obj.collection[1].secAttr; </script> </body> </html> Now the problem is that I don't want to return just one value but multiple ones. For example all entrys with lastAttr=01 should be returned. Therefore I would need something along the line of: for(var i in obj) { if(lastAttr[i]="01") { document.getElementById("outputid").innerHTML = obj.collection[i].firstAttr + " " + obj.collection[i].secAttr; } else { } } Any idea on how to make this work?
If you want to perform a where you need to use Array.prototype.filter: var filteredArr = arr.collection.filter(function(item) { return item.lastAttr == "01"; }); And, finally, you can use Array.prototype.forEach to iterate results and perform some action: var outputElement = document.getElementById("outputid"); filteredArr.forEach(function(item) { // Check that I used insertAdyacentHtml to be sure that all items // will be in the UI! outputElement.insertAdjacentHTML("afterbegin", item.firstAttr + " " + item.secAttr); }); Also, you can do it fluently: var arr = { collection: [{ firstAttr: "hello", secAttr: "world", lastAttr: "01" }, { firstAttr: "hello 2", secAttr: "world 2", lastAttr: "01" }] }; var outputElement = document.getElementById("outputid"); var filteredArr = arr.collection.filter(function(item) { return item.lastAttr == "01"; }).forEach(function(item) { outputElement.insertAdjacentHTML("afterbegin", item.firstAttr + " " + item.secAttr); }); <div id="outputid"></div>
You need to iterate over the collection Array and append the new stuff. Right now you're iterating the outer object and overwriting the .innerHTML each time. var out = document.getElementById("outputid"); for (var i = 0; i < obj.collection.length; i++) { if(obj.collection[i].lastAttr=="01") { out.insertAdjacentHTML("beforeend", obj.collection[i].firstAttr + " " + obj.collection[i].secAttr); } } Note that I used == instead of = for the comparison, and .insertAdjacentHTML instead of .innerHTML.
if you want to replace html try this (someCollection) array; var r = new Array(); var j = -1; r[++j] = '<ul class="list-group">'; for (var i in array) { var d = array[i]; if (d.attribute== somevalue) { r[++j] = '<li class="list-group-item">' r[++j]=d.otherattribute; r[++j] = '</li>'; } } r[++j] = '</ul>'; //for(var b in r) //alert to see the entire html code //{ alert(r[b]);} firstLoadOnPage = false; var list = document.getElementById('SymptomSection'); list.innerHTML = r.join(''); this replaces the inside of element with classname "SymptomSection"
What is the optimal way to load form data into a string and then to localStorage?
Is this the optimal way to load form data into a string and then to localStorage ? I came up with this on my own, and I am not good in programming. It works, for what I need, but I am not sure if it's a bulletproof code? <script> var sg = document.getElementById("selectedGateway"); var sd = document.getElementById("selectedDestination"); var dm = document.getElementById("departureMonth"); var dd = document.getElementById("departureDay"); var dy = document.getElementById("departureYear"); var rm = document.getElementById("returnMonth"); var rd = document.getElementById("returnDay"); var ry = document.getElementById("returnYear"); var ad = document.getElementById("adults"); var ch = document.getElementById("option2"); $("#searchRequestForm").submit(function() { var string = 'From: ' + sg.value + ' \nTo: ' + sd.value + ' \nDeparture: ' + dm.value + '/' + dd.value + '/' + dy.value + ' \nReturn: ' + rm.value + '/' + rd.value + '/' + ry.value + ' \nNumber of adults: ' + ad.value + ' \nNumber of children: ' + ch.value; localStorage.setItem("string", string); }); </script>
I would use something like the following so that I could deal with an object and its properties rather than a big string. Note that other than the jQuery selectors, this is pure JavaScript. Demo: http://jsfiddle.net/grTWc/1/ var data = { sg: $("#selectedGateway").val(), sd: $("#selectedDestination").val() // items here }; localStorage.setItem("mykey", JSON.stringify(data)); To retrieve the data: var data = JSON.parse(localStorage["mykey"]); alert(data.sg); See Also: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify http://api.jquery.com/jQuery.parseJSON/
I prefer a table driven approach so there is no repeated code (DRY): var ids = [ "selectedGateway", "From: ", "selectedDestination", "\nTo :", "departureMonth", "\nDeparture: ", "departureDay", "/", "departureYear", "/", "returnMonth", " \nReturn: ", "returnDay", "/", "returnYear", "/", "adults", " \nNumber of adults: ", "option2", " \nNumber of children: "]; var submitStr = ""; for (var i = 0; i < ids.length; i+=2) { submitStr += ids[i+1] + document.getElementById(ids[i]).value; } localStorage.setItem("string", submitStr);
You could define a function such as the one below to directly get the values by id so then it would be simpler when you build your string. function form(id) { return document.getElementById(id).value; }
mustache - render entire data structure
Is there some way to render all the literal objects and the literal objects within them using mustache? Being a neophyte at this I wondered if the following would work... var data2 = {}; data2["collector"]={"sname":"Collector", "lname":"Collector", "V":[11,12,13,14,15]}; data2["storage"] ={"sname":"Storage", "lname":"Storage", "V":[21,22,23,24,25]}; data2["aux1"] ={"sname":"Aux1", "lname":"Loop High", "V":[31,32,33,34,35]}; data2["aux2"] ={"sname":"Aux2", "lname":"Loop Low", "V":[41,42,43,44,45]}; data2["aux3"] ={"sname":"Aux3", "lname":"Aux3", "V":[51,52,53,54,55]}; data2["aux4"] ={"sname":"Aux4", "lname":"Aux4", "V":[61,62,63,64,65]}; var T2 = "<table border='1'>" + "{{#.}}<tr>" + "{{#.}}" + "<td>{{.}}</td>" + "{{/.}}" + "</tr>" + "{{/.}}" + "</table>" html = Mustache.to_html(T2, data2); but of course it doesn't. I get {{/.}}
Since the goal was to use mustache, here's the final deal using mustache to expand the array. I don't know if Jesse meant to put embedded literal objects in tables within table or not but that was not my goal. I deleted wrap and all from the function in this version as I either didn't need them or understand why they were there. I remain indebted to Jesse for this hint; I doubt I would have come up with anything so clever. var getMustache = function(data, depth) { var r = ""; if (depth == 0) { r=r+"<tr>"; } for(var d in data) { if(data.hasOwnProperty(d)) { if(typeof data[d] =="object") { if (data[d].length) // is it an array? { var T = "{{#" + d + "}}<td>{{.}}</td>{{/" + d + "}}"; r += Mustache.to_html(T, data); } else { r += getMustache(data[d], depth+1); } } else { r += "<td>" + data[d] + "</td>"; } } if (depth == 0) { r=r+"</tr>"; } } return r; } var T2 = "<table border='1'>" + getMustache(data2,0) + "</table>"; html = Mustache.to_html(T2, data2); document.write(html);
Seems like you could just make a recursive function for this - mustache is pretty static, but recursion is perfect for looking up all the nodes in a deep object. Untested hypothetical code: var data2 = {}; data2["collector"]={"sname":"Collector", "lname":"Collector", "V":[11,12,13,14,15]}; data2["storage"] ={"sname":"Storage", "lname":"Storage", "V":[21,22,23,24,25]}; data2["aux1"] ={"sname":"Aux1", "lname":"Loop High", "V":[31,32,33,34,35]}; data2["aux2"] ={"sname":"Aux2", "lname":"Loop Low", "V":[41,42,43,44,45]}; data2["aux3"] ={"sname":"Aux3", "lname":"Aux3", "V":[51,52,53,54,55]}; data2["aux4"] ={"sname":"Aux4", "lname":"Aux4", "V":[61,62,63,64,65]}; var getMustache = function(data, wrap, all, depth){ var r = ""; var depth = depth || 0; for(var d in data){ if(data.hasOwnProperty(d)){ r += "<" + wrap[depth] || all + ">"; if(data[d].length){ r += "{{#" + d + "}}"; r += getMustache(data[d], wrap, all, depth ++); r += "{{/" + d + "}}"; } else { r += "{{" + data[d] + "}}"; } r += "</" + wrap[depth] || all + ">"; } } return r; } var T2 = "<table border='1'>" + getMustache(data2,['tr','td'],'span'); html = Mustache.to_html(T2, data2);
The following works. It doesn't use mustache facilities at all. I plan to change it so that it uses mustache's iteration on the array. var getMustache = function(data, wrap, all, depth) { var r = ""; if (depth == 0) { r=r+"<tr>"; } for(var d in data) { if(data.hasOwnProperty(d)) { if(typeof data[d] =="object") { r += getMustache(data[d], wrap, all, depth+1); } else { r += "<td>" + data[d] + "</td>"; } } if (depth == 0) { r=r+"</tr>"; } } //alert("r=" + r); return r; }