jQuery Check if string is in RegExp - javascript

I want to check if fileExtis in avoidExt and use it in a if...else statement.
var thisFile=$(this).val(); //returns "file.jpg"
var fileExt = thisFile.replace(/^.*\./, ''); //return "jpg"
var avoidExt= new RegExp(/(\.|\/)(bat|exe|cmd|sh|php|pl|cgi|386|dll|com|torrent|js|app|jar|pif|vb|vbscript|wsf|asp|cer|csr|jsp|drv|sys|ade|adp|bas|chm|cpl|crt|csh|fxp|hlp|hta|inf|ins|isp|jse|htaccess|htpasswd|ksh|lnk|mdb|mde|mdt|mdw|msc|msi|msp|mst|ops|pcd|prg|reg|scr|sct|shb|shs|url|vbe|vbs|wsc|wsf|wsh)$/i);

Maybe this will help
var thisFile = $(this).val();
// var fileExt = thisFile.replace(/^.*\./, ''); doesn't need this line
var avoidExt= new RegExp(/(\.|\/)(bat|exe|cmd|sh|php|pl|cgi|386|dll|com|torrent|js|app|jar|pif|vb|vbscript|wsf|asp|cer|csr|jsp|drv|sys|ade|adp|bas|chm|cpl|crt|csh|fxp|hlp|hta|inf|ins|isp|jse|htaccess|htpasswd|ksh|lnk|mdb|mde|mdt|mdw|msc|msi|msp|mst|ops|pcd|prg|reg|scr|sct|shb|shs|url|vbe|vbs|wsc|wsf|wsh)$/i);
if(avoidExt.test(thisFile)){
// exist
}else{
// doesn't exist
}

Check this
var thisFile=$(this).val();
var fileExt = thisFile.replace(/^.*\./, '');
var avoidExt= new RegExp(/(\.|\/)(bat|exe|cmd|sh|php|pl|cgi|386|dll|com|torrent|js|app|jar|pif|vb|vbscript|wsf|asp|cer|csr|jsp|drv|sys|ade|adp|bas|chm|cpl|crt|csh|fxp|hlp|hta|inf|ins|isp|jse|htaccess|htpasswd|ksh|lnk|mdb|mde|mdt|mdw|msc|msi|msp|mst|ops|pcd|prg|reg|scr|sct|shb|shs|url|vbe|vbs|wsc|wsf|wsh)$/i);
if(fileExt.test(avoidExt)){
console.log("EXIST");
}else{
console.log("NOT EXIST");
}

Is not necessary to create a RegExp object, you can use a regexp literal:
var fileExt = $(this).val().replace(/^.*\./, '');
var avoidExt = /(bat|exe|cmd|sh|php|pl|cgi|386|dll|com|torrent|js|app|jar|pif|vb|vbscript|wsf|asp|cer|csr|jsp|drv|sys|ade|adp|bas|chm|cpl|crt|csh|fxp|hlp|hta|inf|ins|isp|jse|htaccess|htpasswd|ksh|lnk|mdb|mde|mdt|mdw|msc|msi|msp|mst|ops|pcd|prg|reg|scr|sct|shb|shs|url|vbe|vbs|wsc|wsf|wsh)/i;
if(fileExt.text(avoidExt)){
// exist
} else {
// doesn't exist
}

You can use RegExp.prototype.test()
var thisFile = "file.jpg";
var fileExt = thisFile.replace(/^.*\./, ''); //return "jpg"
var avoidExt = new RegExp(/(\.|\/)(bat|exe|cmd|sh|php|pl|cgi|386|dll|com|torrent|js|app|jar|pif|vb|vbscript|wsf|asp|cer|csr|jsp|drv|sys|ade|adp|bas|chm|cpl|crt|csh|fxp|hlp|hta|inf|ins|isp|jse|htaccess|htpasswd|ksh|lnk|mdb|mde|mdt|mdw|msc|msi|msp|mst|ops|pcd|prg|reg|scr|sct|shb|shs|url|vbe|vbs|wsc|wsf|wsh)$/i);
console.log(avoidExt.test('.' + fileExt) ? 'fileExt is in' : 'fileExt is not in');
UPDATE : IF...ELSE format
var thisFile = "file.jpg";
var fileExt = thisFile.replace(/^.*\./, ''); //return "jpg"
var avoidExt = new RegExp(/(\.|\/)(bat|exe|cmd|sh|php|pl|cgi|386|dll|com|torrent|js|app|jar|pif|vb|vbscript|wsf|asp|cer|csr|jsp|drv|sys|ade|adp|bas|chm|cpl|crt|csh|fxp|hlp|hta|inf|ins|isp|jse|htaccess|htpasswd|ksh|lnk|mdb|mde|mdt|mdw|msc|msi|msp|mst|ops|pcd|prg|reg|scr|sct|shb|shs|url|vbe|vbs|wsc|wsf|wsh)$/i);
if (avoidExt.test('.' + fileExt))
console.log('fileExt is in')
else
console.log('fileExt is not in');
Or there is no need to extract the extension using regex you can do the following
var thisFile = "file.jpg";
var avoidExt = new RegExp(/(\.|\/)(bat|exe|cmd|sh|php|pl|cgi|386|dll|com|torrent|js|app|jar|pif|vb|vbscript|wsf|asp|cer|csr|jsp|drv|sys|ade|adp|bas|chm|cpl|crt|csh|fxp|hlp|hta|inf|ins|isp|jse|htaccess|htpasswd|ksh|lnk|mdb|mde|mdt|mdw|msc|msi|msp|mst|ops|pcd|prg|reg|scr|sct|shb|shs|url|vbe|vbs|wsc|wsf|wsh)$/i);
console.log(avoidExt.test(thisFile) ? 'fileExt is in' : 'fileExt is not in');

Related

Highlight substring in string with javascript

I have a input for searching in my website and I assign onkeyup event for that.
For example my string is : 'hello world' and when the user types 'llo'(or anything else)show the matched characters as highlighted with the other characters in search list below input.(like google search)
I try this but my code works for the first character not the all characters of string
My code :
//html
<input type="text" onKeyUp="search_customer(this)">
<div class="data_list"></div>
//javascript
function search_customer(input){
var text = input.value;
if(text == ''){
input.nextElementSibling.style.display = 'none';
return;
}
var xhr = new XMLHttpRequest();
xhr.onload = function(){
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
var result = JSON.parse(xhr.responseText);
show_results(result , input);
}else{
alert('request was unsuccessful : ' + xhr.status);
}
}
xhr.open('post' , "<?php echo base_url('deal/search/')?>" , true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('text_search=' + text);
}
function show_results(res , input){
var datalist = input.nextElementSibling;
datalist.style.display = 'block';
if(res.length == 0){
datalist.innerHTML = '<div>nothing matched!<div>';
}else{
var div = document.createElement('div');
for(var i = 0 ; i < res.length ; i++){
if(res[i].full_name.substr(0 , input.value.length) == input.value){
var str = '<strong>'+res[i].full_name.substr(0 , input.value.length)+'</strong>' + res[i].full_name.substr(input.value.length);
var p = div.appendChild(document.createElement('p'));
p.innerHTML = str;
}
}
datalist.replaceChild(div , datalist.firstChild);
}
xhr.open;
}
You can use indexOf to get first index in the matched string and then calculate the last index. Also it's better to use the method slice to be able to use a negative index.
function search_customer(input){
var text = input.value;
if(text == ''){
input.nextElementSibling.style.display = 'none';
return;
}
var xhr = new XMLHttpRequest();
xhr.onload = function(){
if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
var result = JSON.parse(xhr.responseText);
show_results(result , input);
}else{
alert('request was unsuccessful : ' + xhr.status);
}
}
xhr.open('post' , "<?php echo base_url('deal/search/')?>" , true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('text_search=' + text);
}
function show_results(res , input){
var datalist = input.nextElementSibling;
datalist.style.display = 'block';
if(res.length == 0){
datalist.innerHTML = '<div>nothing matched!<div>';
}else{
var div = document.createElement('div');
for(let i = 0 ; i < res.length ; i++){
let search = input.value;
let match;
let lastIndx = (res[i].full_name.length-1) - res[i].full_name.indexOf(search) - (search.length-1);
if(lastIndx == 0){
match = res[i].full_name.slice(res[i].full_name.indexOf(search), res[i].full_name.length);
}else{
match = res[i].full_name.slice(res[i].full_name.indexOf(search), -lastIndx);
}
let str = res[i].full_name.slice(0, res[i].full_name.indexOf(search) ) + '<strong>' + match + '</strong>'+ res[i].full_name.slice(res[i].full_name.length-lastIndx, res[i].full_name.length);
let p = div.appendChild(document.createElement('p'));
p.innerHTML = str;
}
datalist.replaceChild(div , datalist.firstChild);
}
xhr.open;
}

Javascript - FileReader how can I read and process each file at a time among multiple files

I am trying let the user drop multiple excel file and extract desired values from each one of the files and upload it to website ONE FILE AT A TIME.
My code is not working, and I am assuming this is because of the callback problem..
Could anybody help?
Edit: I also added my uploadFile function. I very much appreciate your help.
for(var i = 0; i < fileList.length; i++) {
//console.log(fileList[i]["file"]);
var reader = new FileReader();
var f = fileList[i]["file"];
//var fName = fileList[i]["fileName"];
var excelObject = fileList[i];
reader.onload = function(ev) {
var data = ev.target.result;
if(!rABS) data = new Uint8Array(data);
var wb = XLSX.read(data, {type: rABS ? 'binary' : 'array'});
var einAddress = "B3";
var engCodeAddress = "B1";
var goAddress = "B2";
var errMsg = tabName + " tab or required value is missing";
// Worksheet with the necessary info
try{
var ws = wb.Sheets[tabName];
var ein_cell = ws[einAddress];
ein = (ein_cell ? ein_cell.v.toString() : undefined);
var eng_cell = ws[engCodeAddress];
engCode = (eng_cell ? eng_cell.v.toString() : undefined);
var go_cell = ws[goAddress];
goLocator = (go_cell ? go_cell.v.toString() : undefined);
if(ein == undefined || engCode == undefined || goLocator == undefined){
hasValues = false;
}
excelObject["EngagementCode"] = engCode;
excelObject["GoSystem"] = goLocator;
excelObject["EIN"] = ein;
if(hasValues && isValid){
uploadFile(fileList[i], userInfo);
} else {
noValueErrorHandler(errMsg);
}
} catch(err){
hasValues = false;
}
};
if(rABS) reader.readAsBinaryString(f); else reader.readAsArrayBuffer(f);
}
function uploadFile(f, userInfo) {
// Define the folder path for this example.
var serverRelativeUrlToFolder = listName;
// Get info of the file to be uploaded
var file = f;
var fileInput = file["file"];
var newName = file["fileName"];
var ein = file["EIN"];
var engCode = file["EngagementCode"];
var email = userInfo;
var goLocator = file["GoSystem"];
console.log("file: " + file);
// Get the server URL.
var serverUrl = _spPageContextInfo.siteAbsoluteUrl + "/StatusTracker";
// Initiate method calls using jQuery promises.
// Get the local file as an array buffer.
var getFile = getFileBuffer(fileInput);
getFile.done(function (arrayBuffer) {
// Add the file to the SharePoint folder.
var addFile = addFileToFolder(arrayBuffer, newName);
addFile.done(function (file, status, xhr) {
// Get the list item that corresponds to the uploaded file.
var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
getItem.done(function (listItem, status, xhr) {
// Change the display name and title of the list item.
var changeItem = updateListItem(listItem.d.__metadata);
changeItem.done(function (data, status, xhr) {
processedCount += 1;
if (processedCount < fileCount) {
uploadFile(fileList[processedCount], email);
} else if (processedCount == fileCount){
$("#dropbox").text("Done, drop your next file");
$("#ADMNGrid").data("kendoGrid").dataSource.read();
fileList = [];
alert("Total of " + processedCount + " items are processed!");
}
// Refresh kendo grid and change back the message and empty fileList
//$("#dropbox").text("Drag your Fund/Lower Tier workpaper here ...");
//location.reload(true);
});
changeItem.fail(onError);
});
getItem.fail(onError);
});
addFile.fail(onError);
});
getFile.fail(onError);
You might put the whole thing into an async function and await a Promise for each iteration, forcing the files to be processed in serial. You didn't post your uploadFile, but if you have it return a Promise that resolves once it's done, you could do the following:
async fn() {
for (var i = 0; i < fileList.length; i++) {
await new Promise((resolve, reject) => {
//console.log(fileList[i]["file"]);
var reader = new FileReader();
var f = fileList[i]["file"];
//var fName = fileList[i]["fileName"];
var excelObject = fileList[i];
reader.onload = function(ev) {
var data = ev.target.result;
if (!rABS) data = new Uint8Array(data);
var wb = XLSX.read(data, {
type: rABS ? 'binary' : 'array'
});
var einAddress = "B3";
var engCodeAddress = "B1";
var goAddress = "B2";
var errMsg = tabName + " tab or required value is missing";
// Worksheet with the necessary info
try {
var ws = wb.Sheets[tabName];
var ein_cell = ws[einAddress];
ein = (ein_cell ? ein_cell.v.toString() : undefined);
var eng_cell = ws[engCodeAddress];
engCode = (eng_cell ? eng_cell.v.toString() : undefined);
var go_cell = ws[goAddress];
goLocator = (go_cell ? go_cell.v.toString() : undefined);
if (ein == undefined || engCode == undefined || goLocator == undefined) {
hasValues = false;
}
excelObject["EngagementCode"] = engCode;
excelObject["GoSystem"] = goLocator;
excelObject["EIN"] = ein;
if (hasValues && isValid) {
uploadFile(fileList[i], userInfo)
.then(resolve);
} else {
noValueErrorHandler(errMsg);
reject();
}
} catch (err) {
hasValues = false;
reject();
}
};
if (rABS) reader.readAsBinaryString(f);
else reader.readAsArrayBuffer(f);
});
}
}

xhr.responseText isn't converted to object by JSON.parse()

I have written this function to make ajax-requests to my server that serves JSON objects in string-format. I want to parse these JSON-objects into Javascript objects using JSON.parse(). But when I check the type of the object returned by JSON.parse(), it's a string! Here's the function:
function getDBMatches(){
var xhr = createXHR();
xhr.dropdown = this.parentNode.parentNode.getElementsByClassName("dropdown-content")[0];
xhr.dropdown.innerHTML = "";
if(!xhr.dropdown.classList.contains('show')){
xhr.dropdown.classList.add('show');
}
xhr.onreadystatechange = function(){
if (this.value == ""){
return;
}
if (xhr.readyState == 4){
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
var xhrResponse = xhr.responseText;
alert(xhrResponse); // "[{\"model\": \"workoutcal.liftactivity\", \"pk\": 1, \"fields\": {\"name\": \"benchpress\"}}]"
alert(typeof xhrResponse); // string
var dbMatches = JSON.parse(xhrResponse);
alert(typeof dbMatches); // string! This is what I don't understand.
for(var i = 0; i < dbMatches.length; i++){
var link = document.createElement("a");
link.innerHTML = dbMatches[i]["name"];
link.onclick = function(){
var textbox = link.parentNode.parentNode.getElementsByTagName('input')[0];
textbox.value = link.innerHTML;
xhr.dropdown.innerHTML = "";
};
xhr.dropdown.appendChild(link);
}
} else {
document.getElementById("xhrPar").innerHTML = "Request was unsuccessful: "+xhr.status;
}
}
};
var url = "http://localhost:8000/workoutcal/";
if (this.name == "lift_string"){
url += "get_lifts";
} else if (this.name == "cardio_string"){
url += "get_cardio";
}
url = addURLParam(url, this.name, this.value);
xhr.open("get", url, false);
xhr.send(null);
}
Why isn't the string parsed into a Javascript object?
JSON.parse() returns literal which can be of type Object, String or other types depending upon the parameter being passed to the parse function. Consider the below expression which will return val of type string.
var val = JSON.parse(JSON.stringify("Hello"));

how i to re check only image in upload

// why this code no function if me upload 1.chicken.jpg 180kb 2.chicken.pdf but chicken.pdf follow insert to database
HttpFileCollection hfc = Request.Files;
if (hfc != null)
{
string cekDir = string.Format("{0}\\{1}", ConfigurationManager.AppSettings["docLoc"], id_hazard_report);
string PicDir;
if (Directory.Exists(cekDir)) //check Folder avlalible or not
{
PicDir = cekDir;
}
else
{
DirectoryInfo di = Directory.CreateDirectory(cekDir); // create Folder
PicDir = cekDir;
}
string fullname;
string filename;
FileUpload FileUpload1 = (FileUpload)FormView1.FindControl("FileUpload1");
string fileExt = Path.GetExtension(FileUpload1.FileName); //Get The File Extension
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength >0)
{
///full path name to check exist or not
fullname = string.Format("{0}\\{1}", PicDir, Path.GetFileName(hpf.FileName.Replace(" ", "_")));
bool ex = File.Exists(fullname);
if (hpf == (".jpg") || fileExt == (".gif") || fileExt == (".bmp") || fileExt == (".png") || fileExt == (".jpeg"))
{
if(FileUpload1.FileBytes.Length > 200000)
{
ClientScript.RegisterStartupScript(Type.GetType("System.String"), "messagebox", "<script type=\"text/javascript\">alert('File Tidak boleh lebih dari 200 kb');</script>");
break;
}
if (ex == true)
{
string f = Path.GetFileName(hpf.FileName.Replace(" ", "_"));
string[] a = new string[1];
a = f.Split('.');
filename = string.Format("{0}_{1}.{2}", a.GetValue(0), DateTime.Now.ToString("yymdHm"), a.GetValue(1));
}
else
{
filename = Path.GetFileName(hpf.FileName.Replace(" ", "_")).ToString();
}
///full path name to store in database with new filename
//string[] aa = new string[1];
//filename = string.Format("{0}_{1}.{2}", aa.GetValue(0), DateTime.Now.ToString("yymdHm"), aa.GetValue(1));
fullname = string.Format("{0}\\{1}", PicDir, filename);
hpf.SaveAs(fullname); //save as
InsertHazardDoc(id_hazard_report, filename);
}
else
{
FileUpload1.Focus();
ClientScript.RegisterStartupScript(Type.GetType("System.String"),"messagebox", "<script type=\"text/javascript\">alert('File Bukan Format Gambar');</script>");
break;
}
}
//}
}
}
#endregion
//Page.DataBind();
myfb._success("Hazard Report Succesfully Inserted");
}
catch (Exception ex)
{
myfb._error(ex.ToString());
}
}
// why this code no function if me upload 1.chicken.jpg 180kb 2.chicken.pdf but chicken.pdf follow insert to database
Here you define:
HttpPostedFile hpf = hfc[i];
And then you ask:
if (hpf == (".jpg") || fileExt == (".gif") || fileExt == (".bmp") || fileExt == (".png") || fileExt == (".jpeg"))
But hpf is HttpPostedFile and not a string
Change your code to:
if (fileExt == (".jpg") || fileExt == (".gif") || fileExt == (".bmp") || fileExt == (".png") || fileExt == (".jpeg"))
Additionally, you have a loop for all uploaded files.
Before that loop starts you are getting the file extension then executing the loop:
for (int i = 0; i < hfc.Count; i++)
You need to check the file extension inside of the loop:
for (int i = 0; i < hfc.Count; i++)
string fileExt = Path.GetExtension(hpf.FileName); //Get The File
Otherwise, if your first file has an allowed file extension all files in the upload will be saved.
You method to split the file name based on . is going to cause problems if the file name has a . in it such as FileName.Something.jgp. Instead use Path.GetFileNameWithoutExtension
Your timestamp to give the file a unique name can also cause issues if more than one file with the same name are uploaded at the same second. I see this issue all of the time. You might want to include milliseconds.
If you want to skip the invalid files use continue instead of break:
HttpFileCollection hfc = Request.Files;
if (hfc != null)
{
string cekDir = string.Format("{0}\\{1}", ConfigurationManager.AppSettings["docLoc"], id_hazard_report);
string PicDir;
if (Directory.Exists(cekDir)) //check Folder avlalible or not
{
PicDir = cekDir;
}
else
{
DirectoryInfo di = Directory.CreateDirectory(cekDir); // create Folder
PicDir = cekDir;
}
string fullname;
string filename;
//FileUpload FileUpload1 = (FileUpload)FormView1.FindControl("FileUpload1");
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
///full path name to check exist or not
fullname = string.Format("{0}\\{1}", PicDir, Path.GetFileName(hpf.FileName.Replace(" ", "_")));
// get the file name here.
string fileExt = Path.GetExtension(FileUpload1.FileName); //Get The File Extension
if (FileExt == (".jpg") || fileExt == (".gif") || fileExt == (".bmp") || fileExt == (".png") || fileExt == (".jpeg"))
{
if (hpf.ContentLength.Length > 200000)
{
ClientScript.RegisterStartupScript(Type.GetType("System.String"), "messagebox", "<script type=\"text/javascript\">alert('File Tidak boleh lebih dari 200 kb');</script>");
continue; // break will exit the loop, use continue to go to the next file
}
if (File.Exists(fullname))
{
string f = Path.GetFileNameWithoutExtension(hpf.FileName.Replace(" ", "_"));
string timeStamp = DateTime.Now.ToString("yymdHm"); // this could fail, be more specific with your timestamp;
filename = f + timeStamp + fileExt;
// this will not work correctly if more than one "." in the file name
//string[] a = new string[1];
//a = f.Split('.');
//filename = string.Format("{0}_{1}.{2}", a.GetValue(0), DateTime.Now.ToString("yymdHm"), a.GetValue(1));
}
else
{
filename = Path.GetFileName(hpf.FileName.Replace(" ", "_")).ToString();
}
///full path name to store in database with new filename
//string[] aa = new string[1];
//filename = string.Format("{0}_{1}.{2}", aa.GetValue(0), DateTime.Now.ToString("yymdHm"), aa.GetValue(1));
fullname = string.Format("{0}\\{1}", PicDir, filename);
hpf.SaveAs(fullname); //save as
InsertHazardDoc(id_hazard_report, filename);
}
else
{
FileUpload1.Focus();
ClientScript.RegisterStartupScript(Type.GetType("System.String"), "messagebox", "<script type=\"text/javascript\">alert('File Bukan Format Gambar');</script>");
continue;// break will exit the loop, use continue to go to the next file
}
}
//}
}
}

Dynamically create a find query and have it trigger helper

What I have is a collection. By default the whole collection is shown on the page in a table. The user can then narrow down the results by entering in filter data in 1 or multiple textboxes.
So I have spent the last several hours trying to make this work reactively but failing miserably. The helper is below:
Template.localBoardTemplate.helpers({
localDelivery: function (){
return localBoardColl.find(query);
}
});
Now I have keyup events on the individual textboxes that all trigger the same function to dynamically build the query:
function loadBoardRecords(){
var query = {};
if($('input:text[name=localBoardTripNumSetting]').val() != ""){
query['tripNumber'] = {$regex: new RegExp('^' + $('input:text[name=localBoardTripNumSetting]').val(), 'i')};
}
if($('input:text[name=localBoardLoadNumSetting]').val() != ""){
query['orderLoadNum'] = {$regex: new RegExp('^' + $('input:text[name=localBoardLoadNumSetting]').val(), 'i')};
}
if($('input:text[name=localBoardEquipmentSetting]').val() != ""){
query['equipmentTypeName'] = {$regex: new RegExp('^' + $('input:text[name=localBoardEquipmentSetting]').val(), 'i')};
}
if($('input:text[name=localBoardCustomerSetting]').val() != ""){
query['Customer'] = {$regex: new RegExp('^' + $('input:text[name=localBoardCustomerSetting]').val(), 'i')};
}
if($('input:text[name=localBoardTrailerNumSetting]').val() != ""){
query['trailerNum'] = {$regex: new RegExp('^' + $('input:text[name=localBoardTrailerNumSetting]').val(), 'i')};
}
if($('input:text[name=localBoardPUCitySetting]').val() != ""){
query['puCity'] = {$regex: new RegExp('^' + $('input:text[name=localBoardPUCitySetting]').val(), 'i')};
}
if($('input:text[name=localBoardPUStateSetting]').val() != ""){
query['puState'] = {$regex: new RegExp('^' + $('input:text[name=localBoardPUStateSetting]').val(), 'i')};
}
if($('#localBoardPUDateSetting').val() != ""){
puDate = moment($('#localBoardPUDateSetting').val(), "MM-DD-YYYY").toDate();
query['puDate'] = puDate;
}
if($('input:text[name=localBoardDELCitySetting]').val() != ""){
query['delCity'] = {$regex: new RegExp('^' + $('input:text[name=localBoardDELCitySetting]').val(), 'i')};
}
if($('input:text[name=localBoardDELStateSetting]').val() != ""){
query['delState'] = {$regex: new RegExp('^' + $('input:text[name=localBoardDELStateSetting]').val(), 'i')};
}
if($('#localBoardDELDateSetting').val() != ""){
delDate = moment($('#localBoardDELDateSetting').val(), "MM-DD-YYYY").toDate();
query['delDate'] = delDate;
}
}
Now I have tried using a session variable to hold the query this failed because you can't have nested objects in the session variables. I then tried a package called ReactiveObj and that I couldn't get working either. Heck I even tried a ReactiveArr but that isn't reactive unless you .list it and that doesn't work for the query in the find.
This can't be this hard of a problem and I have probably overlooked something minor. I am hoping someone can point me to the write package or solution for this problem.
A quick-n-dirty code with ReactiveVar
var buildQuery = function(formId) {
// put the code in the loadBoardRecords with the form id
// and return the query
return query;
}
Template.layout.helpers({
localDelivery: function (){
return Template.instance()['resultSet'].get();
}
});
Template.layout.events({
'click .searchButton': function() {
var formId = $(...); // get the id for the form
var cursor = localBoardColl.find(search(formId));
Template.instance()['resultSet'].set(cursor);
}
});
Template.layout.created = function () {
this['resultSet'] = new ReactiecVar(null);
}
Actually you CAN store nested objects in Session variable.
On helpers:
Template.localBoardTemplate.helpers({
localDelivery: function (){
var query = Session.get('QUERY') || {};
return localBoardColl.find(query);
}
});
On events:
function loadBoardRecords(){
var query = Session.get('QUERY') || {};
if($('input:text[name=localBoardTripNumSetting]').val() != ""){
query['tripNumber'] = {$regex: new RegExp('^' + $('input:text[name=localBoardTripNumSetting]').val(), 'i')};
}
.
.
.
.
.
if($('#localBoardDELDateSetting').val() != ""){
delDate = moment($('#localBoardDELDateSetting').val(), "MM-DD-YYYY").toDate();
query['delDate'] = delDate;
}
Session.set('QUERY',query);
}
That is totally possible.
I have solved this through a few bit more trial and error and the help of Thai Trans answer. I used a reativevar variable to store an object. The correct code is as follows:
Helper:
Template.localBoardTemplate.helpers({
localDelivery: function (){
return localBoardColl.find(Template.instance().searchQuery.get());
}
});
The function that creates the query and stores it in the reacvtive-var:
function loadBoardRecords(template){
var query = {};
if($('input:text[name=localBoardTripNumSetting]').val() != ""){
query['tripNumber'] = {$regex: new RegExp('^' + $('input:text[name=localBoardTripNumSetting]').val(), 'i')};
}
if($('input:text[name=localBoardPUStateSetting]').val() != ""){
query['puState'] = {$regex: new RegExp('^' + $('input:text[name=localBoardPUStateSetting]').val(), 'i')};
}
if($('#localBoardPUDateSetting').val() != ""){
puDate = moment($('#localBoardPUDateSetting').val(), "MM-DD-YYYY").toDate();
query['puDate'] = puDate;
}
if($('input:text[name=localBoardDELCitySetting]').val() != ""){
query['delCity'] = {$regex: new RegExp('^' + $('input:text[name=localBoardDELCitySetting]').val(), 'i')};
}
if($('input:text[name=localBoardDELStateSetting]').val() != ""){
query['delState'] = {$regex: new RegExp('^' + $('input:text[name=localBoardDELStateSetting]').val(), 'i')};
}
if($('#localBoardDELDateSetting').val() != ""){
delDate = moment($('#localBoardDELDateSetting').val(), "MM-DD-YYYY").toDate();
query['delDate'] = delDate;
}
template.searchQuery.set( query );
}
This works perfectly. It also still allows for the reactive collection updates even during a users search.

Categories