How to replace multiple values in javascript? - javascript

I have some of this Code:
function writeIslamicDate(adjustment) {
var wdNames = new Array("Ahad","Ithnin","Thulatha","Arbaa","Khams","Jumuah","Sabt");
var iMonthNames = new Array("Muharram","Safar","Rabi'ul Awwal","Rabi'ul Akhir",
"Jumadal Ula","Jumadal Akhira","Rajab","Sha'ban",
"Ramadan","Shawwal","Dhul Qa'ada","Dhul Hijja");
var iDate = kuwaiticalendar(adjustment);
var outputIslamicDate = wdNames[iDate[4]] + ", " + (iDate[5]-1) + " " + iMonthNames[iDate[6]] + " " + iDate[7] + " AH";
return outputIslamicDate;
}
document.write(writeIslamicDate());
Output : Ithnin, 23 Ramadan 1435 AH
?
I want to replace 23 with bengali number ২,৩ ///// or two, three
I watch and try a lot of but couldn't success.. Is there are any to solve this ?
Thanks.
I do like
var someString = (iDate[5]-1) + " " + iMonthNames[iDate[6]] + " " + iDate[7] + " হিজরী";
var outputIslamicDate = somestring.replace(/1/g, "১").replace(/4/g, "৪");
return outputIslamicDate;
but it's not work...

Use regex and the global flag:
str.replace(/word/g, 'word2');

Related

BIRT (maximo data): overloaded fetch script in scripted dataSet

I've inherited a BIRT .rptdesign that isn't returning any records in "preview results." There is one open script involved, as well as a fetch script that has approximately 5 more sql queries inside of it. Much of what I have tried for solutions involves breaking out these queries involved in the fetch script into their own dataSet, and then relating them to the open script (alternatively I've tried forming a joint data set, with no luck). Even after taking out a small query from the fetch script, I'm not able to generate records in result preview. I tried to upload an image of the layout, but don't have the reputation to do so...Please let me know if you need the design file to help visualize where everything is landing!
Open script:
maximoDataSet = MXReportDataSetProvider.create(this.getDataSource().getName(), this.getName());
maximoDataSet.open();
var sqlText = new String();
var printed = params["Printed"].toUpperCase().replace("Y","1");
var printed1 = printed.replace("N","0");
var where = new String(params["where"]);
if (params["Printed"].value)
where += " and workorder.em_printed = '" + printed1 + "' ";
// Add query to sqlText variable.
sqlText = "select workorder.wonum, workorder.workorderid as workorderid1, (select min(w2.workorderid) from maximo.workorder w2 where w2.istask=1 and w2.parent=workorder.wonum and w2.siteid=workorder.siteid) as workorderid, "
+ " workorder.pmnum as pmnum, workorder.targstartdate, workorder.siteid, workorder.description as wdesc, workorder.worktype, a.assetnum, a.description as adesc, a.em_relaymajor, a.em_relayminor, "
+ " workorder.location, l.description as ldesc, a.em_circuit, a.em_manfmodl, a.serialnum, j.em_craft, a.assetuid, "
+ " (select al.description from alndomain al where al.value=j.em_craft and al.domainid='EM_CRAFT') as cdesc, "
+ " (select wt.wtypedesc from maximo.worktype wt where wt.worktype=workorder.worktype) as wtdesc "
+ " from maximo.workorder "
+ " left outer join maximo.asset as a on a.assetnum=workorder.assetnum and a.siteid=workorder.siteid "
+ " left outer join maximo.jobplan as j on j.jpnum=workorder.jpnum and j.pluscrevnum=workorder.pluscjprevnum "
+ " left outer join maximo.locations as l on l.location=workorder.location and l.siteid=workorder.siteid"
// Include the Maximo where clause
+ " where workorder.istask=0 and workorder.status='INPRG' and workorder.siteid='EM' and " + where
;
maximoDataSet.setQuery(sqlText);
Fetch Script:
if (!maximoDataSet.fetch())
return (false);
// Add a line for each output column
// The specific get method should match the data type of the output column.
row["wonum"] = maximoDataSet.getString("wonum");
row["workorderid"] = maximoDataSet.getString("workorderid");
row["workorderid1"] = maximoDataSet.getString("workorderid1");
row["wdesc"] = maximoDataSet.getString("wdesc");
row["worktype"] = maximoDataSet.getString("worktype");
row["assetnum"] = maximoDataSet.getString("assetnum");
row["location"] = maximoDataSet.getString("location");
row["adesc"] = maximoDataSet.getString("adesc");
row["ldesc"] = maximoDataSet.getString("ldesc");
row["em_circuit"] = maximoDataSet.getString("em_circuit");
row["em_manfmodl"] = maximoDataSet.getString("em_manfmodl");
row["serialnum"] = maximoDataSet.getString("serialnum");
row["em_craft"] = maximoDataSet.getString("em_craft");
row["cdesc"] = maximoDataSet.getString("cdesc");
row["wtdesc"] = maximoDataSet.getString("wtdesc");
row["pmnum"] = maximoDataSet.getString("pmnum");
row["siteid"] = maximoDataSet.getString("siteid");
row["assetuid"] = maximoDataSet.getString("assetuid");
row["em_relaymajor"] = maximoDataSet.getString("em_relaymajor");
row["em_relayminor"] = maximoDataSet.getString("em_relayminor");
row["targstartdate"] = maximoDataSet.getTimestamp("targstartdate");
// Long Description
longDescDataSet = MXReportDataSetProvider.create(this.getDataSource().getName(), "longDescDataSet");
longDescDataSet.open();
longDescSQL = "select longdescription.ldtext "
+ "from longdescription "
+ "where longdescription.ldownertable='WORKORDER' and longdescription.ldownercol='DESCRIPTION' "
+ "and longdescription.ldownercol='DESCRIPTION' "
+ "and longdescription.ldkey=?";
longDescDataSet.setQuery(longDescSQL);
longDescDataSet.setQueryParameterValue(1, maximoDataSet.getString("workorderid"));
if(longDescDataSet.fetch()) {
row["longdesc"] = longDescDataSet.getString("ldtext");
}
longDescDataSet.close();
// End Long Description
// Last Major
lastmajorDataSet = MXReportDataSetProvider.create(this.getDataSource().getName(), "lastmajorDataSet");
lastmajorDataSet.open();
lastmajorSQL = "select workorder.wonum as wn1, workorder.workorderid as wid1, workorder.description as d1, p.frequency as f1, p.frequnit as fu1, "
+ "p.lastcompdate as lc1, p.extdate as e1, p.nextdate as n1, workorder.targstartdate as tsd1 "
+ "from workorder "
+ "join pm as p on p.pmnum=workorder.pmnum and p.siteid=workorder.siteid "
+ "where workorder.istask = 0 and workorder.actfinish = (select max(w1.actfinish) from maximo.workorder as w1 where w1.wonum=workorder.wonum and w1.siteid=workorder.siteid) "
+ "and workorder.worktype = 'MAJPM' and workorder.assetnum=? and workorder.siteid=? ";
lastmajorDataSet.setQuery(lastmajorSQL);
lastmajorDataSet.setQueryParameterValue(1, maximoDataSet.getString("assetnum"));
lastmajorDataSet.setQueryParameterValue(2, maximoDataSet.getString("siteid"));
if(lastmajorDataSet.fetch()) {
row["wn1"] = lastmajorDataSet.getString("wn1");
row["wid1"] = lastmajorDataSet.getString("wid1");
row["d1"] = lastmajorDataSet.getString("d1");
row["f1"] = lastmajorDataSet.getString("f1");
row["lc1"] = lastmajorDataSet.getTimestamp("lc1");
row["fu1"] = lastmajorDataSet.getString("fu1");
row["e1"] = lastmajorDataSet.getTimestamp("e1");
row["n1"] = lastmajorDataSet.getTimestamp("n1");
row["tsd1"] = lastmajorDataSet.getTimestamp("tsd1");
}
lastmajorDataSet.close();
// End Last Major
// Last Major Initials
lastmajorIDataSet = MXReportDataSetProvider.create(this.getDataSource().getName(), "lastmajorIDataSet");
lastmajorIDataSet.open();
lastmajorISQL =" WITH x(key, val, rnum) AS "
+ " (SELECT refwo, em_initials, row_number() over(partition by refwo) "
+ " from maximo.labtrans as labtrans "
+ " join maximo.person as person on person.personid=labtrans.laborcode where labtrans.refwo='" + row["wn1"] + "' and labtrans.siteid=?), "
+ " y(key, str, cnt, cnt_max) AS "
+ " ( SELECT key, VARCHAR('', 1000), 0, MAX(rnum) "
+ " FROM x "
+ " GROUP BY key "
+ " UNION ALL "
+ " SELECT y.key, y.str || RTRIM(CHAR(x.val)) || ',', y.cnt + 1, y.cnt_max "
+ " FROM x, y "
+ " WHERE x.key = y.key AND "
+ " x.rnum = y.cnt + 1 AND "
+ " y.cnt < y.cnt_max ) "
+ " SELECT key, str "
+ " FROM y "
+ " WHERE y.cnt = y.cnt_max ";
lastmajorIDataSet.setQuery(lastmajorISQL);
//lastmajorIDataSet.setQueryParameterValue(1, lastmajorDataSet.getString("wn1"));
lastmajorIDataSet.setQueryParameterValue(1, maximoDataSet.getString("siteid"));
if(lastmajorIDataSet.fetch()) {
row["str"] = lastmajorIDataSet.getString("str");
}
lastmajorIDataSet.close();
// End Last Major Initials
// Last Major Long Description
LMlongDescDataSet = MXReportDataSetProvider.create(this.getDataSource().getName(), "LMlongDescDataSet");
LMlongDescDataSet.open();
LMlongDescSQL = "select longdescription.ldtext as ldtext1 "
+ "from longdescription "
+ "where longdescription.ldownertable='WORKORDER' and longdescription.ldownercol='DESCRIPTION' "
+ "and longdescription.ldkey=" + row["wid1"];
LMlongDescDataSet.setQuery(LMlongDescSQL);
//LMlongDescDataSet.setQueryParameterValue(1, lastmajorDataSet.getString("wid1"));
if(LMlongDescDataSet.fetch()) {
row["longdesc1"] = LMlongDescDataSet.getString("ldtext1");
}
LMlongDescDataSet.close();
// End Last Major Long Description
// Last Minor
lastminorDataSet = MXReportDataSetProvider.create(this.getDataSource().getName(), "lastminorDataSet");
lastminorDataSet.open();
lastminorSQL = "select workorder.wonum as wn2, workorder.workorderid as wid2, workorder.description as d2, p.frequency as f2, p.frequnit as fu2, "
+ "p.lastcompdate as lc2, p.extdate as e2, p.nextdate as n2, workorder.targstartdate as tsd2 "
+ "from workorder "
+ "join pm as p on p.pmnum=workorder.pmnum and p.siteid=workorder.siteid "
+ "where workorder.istask = 0 and workorder.actfinish = (select max(w1.actfinish) from maximo.workorder as w1 where w1.wonum=workorder.wonum and w1.siteid=workorder.siteid) "
+ "and workorder.worktype = 'MINPM' and workorder.assetnum=? and workorder.siteid= ? ";
lastminorDataSet.setQuery(lastminorSQL);
lastminorDataSet.setQueryParameterValue(1, maximoDataSet.getString("assetnum"));
lastminorDataSet.setQueryParameterValue(2, maximoDataSet.getString("siteid"));
if(lastminorDataSet.fetch()) {
row["wn2"] = lastminorDataSet.getString("wn2");
row["wid2"] = lastminorDataSet.getString("wid2");
row["d2"] = lastminorDataSet.getString("d2");
row["f2"] = lastminorDataSet.getString("f2");
row["lc2"] = lastminorDataSet.getTimestamp("lc2");
row["fu2"] = lastminorDataSet.getString("fu2");
row["e2"] = lastminorDataSet.getTimestamp("e2");
row["n2"] = lastminorDataSet.getTimestamp("n2");
row["tsd2"] = lastminorDataSet.getTimestamp("tsd2");
}
lastminorDataSet.close();
// End Last Minor
// Last Minor Initials
lastminorIDataSet = MXReportDataSetProvider.create(this.getDataSource().getName(), "lastminorIDataSet");
lastminorIDataSet.open();
lastminorISQL =" WITH x(key, val, rnum) AS "
+ " (SELECT refwo, em_initials, row_number() over(partition by refwo) "
+ " from maximo.labtrans as labtrans "
+ " join maximo.person as person on person.personid=labtrans.laborcode where labtrans.refwo='" + row["wn2"] + "' and labtrans.siteid=?), "
+ " y(key, str1, cnt, cnt_max) AS "
+ " ( SELECT key, VARCHAR('', 1000), 0, MAX(rnum) "
+ " FROM x "
+ " GROUP BY key "
+ " UNION ALL "
+ " SELECT y.key, y.str1 || RTRIM(CHAR(x.val)) || ',', y.cnt + 1, y.cnt_max "
+ " FROM x, y "
+ " WHERE x.key = y.key AND "
+ " x.rnum = y.cnt + 1 AND "
+ " y.cnt < y.cnt_max ) "
+ " SELECT key, str1 "
+ " FROM y "
+ " WHERE y.cnt = y.cnt_max ";
lastminorIDataSet.setQuery(lastminorISQL);
//lastminorIDataSet.setQueryParameterValue(1, lastminorDataSet.getString("wn2"));
lastminorIDataSet.setQueryParameterValue(1, maximoDataSet.getString("siteid"));
if(lastminorIDataSet.fetch()) {
row["str1"] = lastminorIDataSet.getString("str1");
}
lastminorIDataSet.close();
// End Last Minor Initials
// Last Minor Long Description
LM2longDescDataSet = MXReportDataSetProvider.create(this.getDataSource().getName(), "LM2longDescDataSet");
LM2longDescDataSet.open();
LM2longDescSQL = "select longdescription.ldtext as ldtext2 "
+ "from longdescription "
+ "where longdescription.ldownertable='WORKORDER' and longdescription.ldownercol='DESCRIPTION' "
+ "and longdescription.ldkey=" + row["wid2"];
LM2longDescDataSet.setQuery(LM2longDescSQL);
//LM2longDescDataSet.setQueryParameterValue(1, lastminorDataSet.getString("wid2"));
if(LM2longDescDataSet.fetch()) {
row["longdesc2"] = LM2longDescDataSet.getString("ldtext2");
}
LM2longDescDataSet.close();
// End Last Minor Long Description
// Asset Long Description
AlongDescDataSet = MXReportDataSetProvider.create(this.getDataSource().getName(), "AlongDescDataSet");
AlongDescDataSet.open();
AlongDescSQL = "select longdescription.ldtext as ldtext3 "
+ "from longdescription "
+ "where longdescription.ldownertable='ASSET' and longdescription.ldownercol='DESCRIPTION' "
+ "and longdescription.ldkey=?";
AlongDescDataSet.setQuery(AlongDescSQL);
AlongDescDataSet.setQueryParameterValue(1, maximoDataSet.getString("assetuid"));
if(AlongDescDataSet.fetch()) {
row["longdesc3"] = AlongDescDataSet.getString("ldtext3");
}
AlongDescDataSet.close();
// End Asset Long Description
myTxn = MXReportTxnProvider.create(this.getDataSource().getName());
myStmt = myTxn.createStatement();
myStmt.setQuery("update workorder set workorder.em_printed = '1' where workorder.em_printed = '0' and workorder.workorderid = ? ");
myStmt.setQueryParameterValue(1,row["workorderid1"]);
//myStmt.setQueryParameterValue(2,"'"+row["siteid"]+"'");
myTxn.save();
return (true);
enter image description here

How to return a value in the only non-blank column in a range for sendEmail function in Google App Scripts

The issue is: I can't find a way to return the value for 'Course' because each form submission generates a new row where the name of the course is spread over columns E to M (column 4 through 12).
In each row, there is only one 'Course' name in one of the columns from E to M (e.g only in F) and all other columns are blank. (Users can only select one course and all the other columns will be blank. I have to categorize the courses into the 9 columns because of the page breaks in order to split the sheer number of options that users select the course from.) How do I return the value of the only non blank cell from E to M which will be entered in the email ?
I was advised to insert the entire findCourse function inside of the sendEmail function before any of the other code. I did so but I have still been receiving failure notifications of the Google App Scripts: TypeError: Cannot read property "values" from undefined. (line 14, file "Code") (referring to var value = e.values[i])
The full code below:
function sendEmail(e) {
function findCourse (e){
var courseToTake;
//loop through values
for ( var i = 4; i <=12; i ++){
//pull value into variable
var value = e.values[i];
if (value != undefined){
//if we find an actual string value, set the course to take variable
courseToTake = value;
}
}
return courseToTake;
}
var Name = e.namedValues["Full name as appear in NRIC"];
var Course = findCourse();
var Start = e.values[14];
var End = e.values[15];
var StartTime = e.values[24];
var EndTime = e.values[25];
var Details = e.values[13];
var Cost = e.values[17];
var Email = e.values[18];
var ROname = e.values[19];
var ROemail = e.values[20];
var Location = e.values[23];
var subject = "Training Approval Request for " + Course;
var message = "<p >" + "Dear " + ROname + "<p />"
+ Name + " seeks your approval to attend the " + Course + ". The details are as follow:"
+ "<p >" + "<b>Date:</b> " + Start + " - " + End + " <br />"
+ "<b>Time:</b> " + StartTime + " - " + EndTime + " <br />"
+ "<b>Location:</b> " + Location + " <br />"
+ "<b>Course objectives and benefits:</b> " + Details + " <br />"
+ "<b>Course fees:</b> " + "$" + Cost + " <br />" + "<p />"
+ "Please reply directly to this email for your approval or if you have any questions/comments. Thank you. "
MailApp.sendEmail(ROemail, Email, subject, message);
}
After rearranging findCourse as its own function: sorry if I made any mistakes here but i'll try my best to follow all suggestions. If i've added in Logger.log(e) correctly, both functions seem to be undefined
function sendEmail(e) {
Logger.log(e);
var Name = e.values[2];
var Course = findCourse();
var Start = e.values[14];
var End = e.values[15];
var StartTime = e.values[24];
var EndTime = e.values[25];
var Details = e.values[13];
var Cost = e.values[17];
var Email = e.values[18];
var ROname = e.values[19];
var ROemail = e.values[20];
var Location = e.values[23];
var subject = "Training Approval Request for " + Course;
var message = "<p >" + "Dear " + ROname + "<p />"
+ Name + " seeks your approval to attend the " + Course + ". The details are as follow:"
+ "<p >" + "<b>Date:</b> " + Start + " - " + End + " <br />"
+ "<b>Time:</b> " + StartTime + " - " + EndTime + " <br />"
+ "<b>Location:</b> " + Location + " <br />"
+ "<b>Course objectives and benefits:</b> " + Details + " <br />"
+ "<b>Course fees:</b> " + "$" + Cost + " <br />" + "<p />"
+ "Please reply directly to this email for your approval or if you have any questions/comments. Thank you. "
MailApp.sendEmail(ROemail, Email, subject, message);
}
function findCourse (e){
var courseToTake;
//loop through values
for ( var i = 4; i <=12; i ++){
//pull value into variable
var value = e.values[i];
if (value != undefined){
//if we find an actual string value, set the course to take variable
courseToTake = value;
}
}
return courseToTake;
var courseToTake = findCourse(e);
Logger.log(e);
}
I will really deeply appreciate any help or alternative solutions here.
Thank you!
What I changed in your code to address your question:
I assigned the onFormSubmit trigger to your sendEmail function so the event object would no longer be undefined
I added a call to findCourse() so your course variable would no longer be undefined
I fixed the undefined check by changing if(value != undefined) to if(typeof value !== 'undefined')
I added a check for a blank value (This was the important bit in the logic after the faulty undefined check) if(value != '')
Explanation:
To trigger the event, an installable trigger needs to be setup for the On Form Submit event that points to your sendEmail function. This can be found in Resources -> Current Project Triggers
To retrieve the course, you need to call your function findCourse() and pass in the e event object. Example: var course = findCourse(e);. This will assign the return value from findCourse(e); to the course variable. You can then use this variable like normal within the rest of your statements.
When checking for undefined, you need to use typeof and then check for the string of 'undefined', or your check will ironically throw an undefined exception.
The values of the form submit should not be undefined, blank values should just be blank strings. so checking for non-blank strings was necessary to get the course name from the values array.
Fixed Code:
function sendEmail(e) {
Logger.log(e)
var course = findCourse(e);
var Name = e.values[19];
var Start = e.values[12];
var End = e.values[14];
var StartTime = e.values[13];
var EndTime = e.values[15];
var Details = e.values[11];
var Cost = e.values[17];
var Email = e.values[20];
var ROname = e.values[21];
var ROemail = e.values[22];
var Location = e.values[16];
var subject = "Training Approval Request for " + course;
var message = "<p >" + "Dear " + ROname + "<p />"
+ Name + " seeks your approval to attend the " + course + ". The details are as follow:"
+ "<p >" + "<b>Date:</b> " + Start + " - " + End + " <br />"
+ "<b>Time:</b> " + StartTime + " - " + EndTime + " <br />"
+ "<b>Location:</b> " + Location + " <br />"
+ "<b>Course objectives and benefits:</b> " + Details + " <br />"
+ "<b>Course fees:</b> " + "$" + Cost + " <br />" + "<p />"
+ "Please reply directly to this email for your approval or if you have any questions/comments. Thank you. "
MailApp.sendEmail(ROemail, Email+";" + "redactedEmail", subject, message);
}
function findCourse (e){
var courseToTake;
//loop through values
for ( var i = 2; i <=10; i ++){
//pull value into variable
var value = e.values[i];
if (typeof value !== 'undefined'){ //If value is defined
if(value != ''){ //If value is not blank
//if we find an actual non-blank string value, set the course to take variable
courseToTake = value;
}
}
}
return courseToTake;
}

Concat first item of array to first itiem of second array JavaScript

how can I concat more rationally first item of array to first of second array and so on? Basically automate console.log here is the code:
$("button#search").on("click", function(){
var inputVal = $("input#text").val();
$.getJSON("https://en.wikipedia.org/w/api.php?action=opensearch&search=" + inputVal +"&limit=5&namespace=0&format=json&callback=?", function(json) {
var itemName = $.each(json[1], function(i, val){
})
var itemDescription = $.each(json[2], function(i, val){
})
var itemLink = $.each(json[3], function(i, val){
})
console.log(itemName[0] + " " + itemDescription[0] + " " + itemLink[0]);
console.log(itemName[1] + " " + itemDescription[1] + " " + itemLink[1]);
console.log(itemName[2] + " " + itemDescription[2] + " " + itemLink[2]);
console.log(itemName[3] + " " + itemDescription[3] + " " + itemLink[3]);
console.log(itemName[4] + " " + itemDescription[4] + " " + itemLink[4]);
})//EOF getJSON
});//EOF button click
I believe this is what you are looking for:
for (var i = 0; i < itemName.length; i++) {
console.log(itemName[i] + " " + itemDescription[i] + " " + itemLink[i]);
}
If arrays have the same length, you could use map
var result = $.map(json[1], function(i, val){
var row = val + " " + json[2][i] + " " + json[3][i];
console.log(row);
return row;
}
Also you can use that result later, e.g.
console.log(result[0]);
Using es6 you can do the following:
(in your getJson callback):
function (json) {
const [value, optionsJ, descriptionsJ, linksJ] = json;
let whatIwant = [];
// choose one to loop through since you know they will all be the same length:
optionsJ.forEach(function (option, index) {
whatIwant.push({option: option, description: descriptionJ[index], link: linksJ[index]});
});
// use whatIwant here**
}
Your new whatIwant array will then contain objects for each set.

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;
}

AJAX search - no results returns last line

I am trying to implement a search box that will search a particular play (AJAX file) for any instances of the word, if the word is found it then outputs that line. My problem is that if no results are found of the word instead of continuing to show the entire play it outputs the last line of the play only.
My function:
function searchResults(query) {
var temp = "\\b" + query + "\\b";
var regex_query = new RegExp(temp, "gi");
var currentLine;
var num_matching_lines = 0;
$("#mainOutput").empty();
$("LINE", current_play_dom).each(function () {
var line = this;
currentLine = $(this).text();
matchesLine = currentLine.replace(regex_query, '<span class="query_match">' + query + '</span>');
if ( currentLine.search(regex_query) > 0 ) {
num_matching_lines++
$("#mainOutput").append("<br /><p class='speaker_match'>"+ $(line).parent().find('SPEAKER').text() +"</p>");
$("#mainOutput").append("<p class='act_match'>"+ $(line).parent().parent().parent().children(':first-child').text()+"</p>");
$("#mainOutput").append("<p class='scene_match'>"+ $(line).parent().parent().children(':first-child').text() +"</p>");
$("#mainOutput").append("<p>" + matchesLine + "</p>");
$("#mainOutput").append("<br>");
}
});
$("#mainOutput").append("<p>" + matchesLine + "</p>");
$("#sideInfo").append("<p>Found " + query + " in " + num_matching_lines + " lines</p>");
}
Also as a side question is there a neater way to do this:
$(line).parent().parent().parent().children(':first-child')

Categories