Javascript to show any/all query values in the URL - javascript

I am working on a document list with a filter menu to pair down the listing via query strings. I want to display all current query values in a designated div, which I have working. The problem that I have now is that I have each category individually coded in the JS, which causes an "undefined" value to display if there is no query for that category.
I want to display ONLY the values that are represented in the query. I have been trying to create an array, but my JS is spotty at best and this has been kludged-together from multiple sources.
Any suggestions?
Here is my current js:
function getQueryVariable(variable)
{
try{
q = location.search.substring(1);
v = q.split("&");
for( var i = 0; i < v.length; i++ ){
p = v[i].split("=");
if( p[0] == variable ){
if( p[1].indexOf('_') != -1 ){
n = [];
for( var j = 0; j < p[1].split('_').length; j++ ){
n.push(p[1].split('_')[j]);
}
str = "";
for( var k = 0; k < n.length; k++ ){
str += n[k] + ' ';
}
return str.trim();
}
else{
return p[1];
}
}
}
}
catch (e){
console.log(e);
}
}
if(document.location.search.length) {
// query string exists
$p( "div#filterContainer" ).html(
"<div class='litType'><ul class='ct-list'><li class='ct-list-elem'>"
+getQueryVariable('application')
+"</li>"+
"<li class='ct-list-elem'>"
+getQueryVariable('year')
+"</li>"+
"<li class='ct-list-elem'>"
+getQueryVariable('industry')+
"</li>"+
"<li class='ct-list-elem'>"
+getQueryVariable('literature_type')
+
"</li></ul></div>" );
} else {
// no query string exists
$p( "div#filterContainer" ).html(
"No filters are being applied." );
}

Related

Slow execution of a loop in Apps Script

Basically what I am looking for is any recommendations you can provide me to make this piece of code to execute faster.
The intention of this piece of code its basically by testing some conditions obtain a score and the questions related for each profile selected, and print those scores in the "Results Sheet" and print the questions in Sheets assigned with the name of the profile.
Through some quick and basic testing I discovered whenever the loop starts to print either the results or the questions its where the slow execute starts.
Sorry for the mess on the code I just started programming in Apps
Script several weeks ago.
EDIT
To be quite more specific Im trying to find out if there is any work around to print the questions in the different sheets and values of the profiles. I took a look at the similar question and he addresses a loop using for..in, Im still trying to find out if there is any other logical process I can do to get those values.
var iGrade1 = 0;
var iGrade2 = 0.5;
var iGrade3 = 1;
var resultsSheet = SpreadsheetApp.getActive().getSheetByName('Results');
var iStartingColumn = 5;
var iCellD = 'D';
var iCellE = 'E';
var iTotCounter = 2;
var amountProfiles = profileSheet.getRange
(2, perfilSheet.getLastColumn()).getValue();
var iTotPerf = 0;
var iPT = 1;
var aResizeP = 1;
for( i = 2; i< questionsSheet.getLastRow() ; i++ ){
//Range
sBI = 'B' + i;
sDI = 'D' + i;
//Copies values like 1|2|3|4|, 3|4|, 2|3|, etc.
profileCodes = questionsSheet.getRange(sDI).getValue();
for(j = 0; j < amountProfiles; j++){
//There is a checkbox where user selects if he wants that profile or not
if(profileSheet.getRange(1,iStartingColumn).getValue()
=== 'Yes'){
var sheetProfile = SpreadsheetApp.getActive().getSheetByName
(profileSheet.getRange(3, iStartingColumn).getValue());
var totProfile = profileSheet.getRange(perfilSheet.getLastRow(), iStartingColumn).getValue();
//User can select in a checkbox between 'Bad' 'Regular' and 'Good'
if( ( questionsSheet.getRange( sBI ).getValue() === '× Bad' ) ){
if(profileCodes.split("|").indexOf( String( perfilSheet.getRange(2, iStartingColumn).getValue() ) ) > -1 ){
iTotPerf = iTotPerf + iGrade1; }
}
else if( ( questionsSheet.getRange( sBI ).getValue() === ' ± Regular' ) ){
if( profileCodes.split("|").indexOf( String( perfilSheet.getRange(2, iStartingColumn).getValue() ) ) > -1 ){
iTotPerf = iTotPerf + iGrade2; }
}
else if( ( questionsSheet.getRange( sBI ).getValue() === '✓ Good' ) ){
if(profileCodes.split("|").indexOf( String( perfilSheet.getRange(2, iStartingColumn).getValue() ) ) > -1 ){
iTotPerf = iTotPerf + iGrade3; }
}
if ( profileCodes.split('|').indexOf(String
(perfilSheet.getRange(2, iStartingColumn).getValue()))
> -1){
questionsSheet.getRange('A' + i + ':' + 'C' + i)
.copyTo(sheetProfile.getRange('A' + iPT),SpreadsheetApp
.CopyPasteType.PASTE_NORMAL,false);
sheetProfile.autoResizeColumn(aResizeP);
}
if(iTotPerf != 0){
resultadosSheet.getRange(iCellD + iTotCounter).setValue(resultadosSheet.getRange(iCellD + iTotCounter).getValue() + iTotPerf);
resultsSheet.getRange(iCellE + iTotCounter).setValue( ( (resultsSheet.getRange(iCellD + iTotCounter).getValue() * 100)/ totPerfil )/ 100);
}
}
iTotPerf = 0;
iTotCounter++;
iStartingColumn++;
}
iPT += 1;
iTotCounter = 2;
iStartingColumn = 5;
}

JS for loop not working

I have a for loop which looks like this:
for (var i = 0; i < list.length; i++) {
It is looping through Firebase data in the database and returning all the data in the database.
However, I want it to only go up to the first 10 database items. So I changed the loop to:
for (var i = 0; i < 9; i++) {
But this fails to display any results when the there are less than 10 pieces of data in the database. However, if I set the number to however many objects I have in the database, for example 10 because I have 10 objects, it displays them all. But any less than this number and I just get a blank webpage.
Here is the webpage when I have 10 objects in my Firebase database:
And here it is when I remove one of those objects:
I have no idea why this is happening - The logic is correct - if i is less than 9 then display the data - But instead it only displays it when it equals 9.
Here is the full JS:
function refreshUI(list) {
var lis = '';
var lis2 = '';
var lis3 = '';
var lis4 = '';
for (var i = 0; i <= 9; i++) {
lis += '<li data-key="' + list[i].key + '" onclick="addText(event)">' + list[i].book + '</li>';
lis2 += genLinks(list[i].key, list[i].book)
};
for (var i = 10; i < list.length; i++) {
lis3 += '<li data-key="' + list[i].key + '" onclick="addText(event)">' + list[i].book + '</li>';
lis4 += genLinks(list[i].key, list[i].book)
};
document.getElementById('bookList').innerHTML = lis;
document.getElementById('bookList2').innerHTML = lis2;
document.getElementById('bookList3').innerHTML = lis3;
document.getElementById('bookList4').innerHTML = lis4;
};
function genLinks(key, bkName) {
var links = '';
links += '<img src="images/bin.png" style="width: 24px; height: 24px; transform: translateY(-7px); opacity: .4;"></img> ';
return links;
};
function del(key, bkName) {
var response = confirm("Are certain about removing \"" + bkName + "\" from the list?");
if (response == true) {
// build the FB endpoint to the item in movies collection
var deleteBookRef = buildEndPoint(key);
deleteBookRef.remove();
}
}
function buildEndPoint (key) {
return new Firebase('https://project04-167712.firebaseio.com/books/' + key);
}
// this will get fired on inital load as well as when ever there is a change in the data
bookList.on("value", function(snapshot) {
var data = snapshot.val();
var list = [];
for (var key in data) {
if (data.hasOwnProperty(key)) {
book = data[key].book ? data[key].book : '';
if (book.trim().length > 0) {
list.push({
book: book,
key: key
})
}
}
}
// refresh the UI
refreshUI(list);
});
If anybody has any help I'd greatly appreciate it!
When the list size is shorter than 10, you will get an error in the loop because you will eventually address a property (like key) that does not exist on list[i] (since it is undefined). If you would check the console, you would notice that this error is reported.
To fix this, change the condition of the first for loop like this:
for (var i = 0; i < Math.min(10, list.length); i++) {
This way, the loop will never iterate to an entry that does not exist. It will stop after 9 or after list.length-1 whichever comes first.
Alternatively, you can just put the two conditions with an && operator:
for (var i = 0; i < 10 && i < list.length; i++) {

Generating Radio Button Result Depending On TextArea Value

A few days ago I did not manage to generate a result from my radio button, I managed to solve that problem now. My other problem is how do I generate ONLY few set of the radio button depending on TextArea value changes;
For Example in this code
<script language="javascript" type="text/javascript">
function generatetest() {
codeOne = document.docContainer.text1.value;
codeTwo = document.docContainer.number2.value;
function firstType(){
var codeFour = 0;
for( i = 0; i < document.docContainer.radio4.length; i++ )
{
if( document.docContainer.radio4[i].checked == true )
codeFour = document.docContainer.radio4[i].value;
}
var codeTen = 0;
for( i = 0; i < document.docContainer.radio10.length; i++ )
{
if( document.docContainer.radio10[i].checked == true )
codeTen = document.docContainer.radio10[i].value;
}
document.docContainer.textarea12.value = codeOne + codeTwo + codeFour + codeTen;
}
function secondType(){
var codeSix = 0;
for( i = 0; i < document.docContainer.radio6.length; i++ )
{
if( document.docContainer.radio6[i].checked == true )
codeFour = document.docContainer.radio6[i].value;
}
var codeEleven = 0;
for( i = 0; i < document.docContainer.radio11.length; i++ )
{
if( document.docContainer.radio11[i].checked == true )
codeTen = document.docContainer.radio11[i].value;
}
document.docContainer.textarea12.value = codeOne + codeTwo + codeSix + codeEleven
}
if (document.docContainer.number2.value="1")
{
firstType();
}
else if (document.docContainer.number2.value="2")
{
secondType();
}
}
</script>
The code is working, problem is, even though I insert the value on textarea "number2" as "2", the code still generate firstType() result
Am Im using wrong if-statement or what and how do I go around about this?
Your code could be more fun to read, but Putting quotes around your numbers is causing javascript to treat them like text. Is this what you want to be doing?

How to implement .indexof for an array of strings?

How can I simplify below code? How can I get rid of the if statements? I want to highlight some lines in ajax response. Right now I have two strings to compare = two ifs. This number will increase so I am thinking of doing this some other way - using an array of the strings that needs to be highlighted in case the string is part of data_array element.
I prefer a solution in javascript only but jQuery is ok too.
data_array=data.split('<BR>');
for(var i=0, len=data_array.length; i < len; i++){
if (data_array[i].indexOf('Conflict discovered') >= 0){
data_array[i]="<span class='red'>"+data_array[i]+"</span>";
}
if (data_array[i].indexOf('Syntax error') >= 0){
data_array[i]="<span class='red'>"+data_array[i]+"</span>";
}
}
data=data_array.join('<BR>');
Add more elements to the array as desired :)
data.replace( /<br>/ig, '\n' ).replace(
new RegExp( '^(.*(?:' + [
'Conflict discovered'
, 'Syntax error'
].join( '|' ) + ').*)$', 'gm' )
, '<span class="red">$1</span>' ).replace( /\n/g, '<br>' );
explanation:
replace <br> tags with line breaks
make a regexp: ^(.*(?:Conflict discovered|Syntax error).*)$
surround matches with <span class="red"> ... </span>
turn line breaks back in to <br> tags
Why not add another for loop?
data_array=data.split('<BR>');
var stringsToFind = ['Conflict discovered', 'Syntax error'];
for (var i = 0; i < data_array.length; i++) {
for (var j = 0; j < stringsToFind.length; j++) {
var currItem = data_array[i];
if (currItem.indexOf(stringsToFind[j]) >= 0) {
data_array[i]='<span class="red">' + currItem + '</span>';
}
}
}
data = data_array.join('<BR>');
jQuery (note, may be slower, and I haven't tested this yet)
data_array=data.split('<BR>');
var stringsToFind = ['Conflict discovered', 'Syntax error'];
$.each(data_array, function(i, item) {
$.each(stringsToFind, function(j, s) {
if (item.indexOf(s) >= 0) {
data_array[i]='<span class="red">' + item + '</span>';
}
}
});
data = data_array.join('<BR>');
var data_array = data.split('<BR>');
var errMsgs = ['Conflict discovered', 'Syntax error'];
data_array = data_array.map(function(data_rec) {
var isAnError = errMsgs.some(function (errMsg) {
return data_rec.indexOf(errMsg) >= 0;
});
if (isAnError) {
return "<span class='red'>" + data_rec + '</span>';
} else {
return data_rec;
}
});
jsBin demo
var highlightWords = ['Conflict discovered', 'Syntax error', 'Simply cool'];
for(i=0; i<highlightWords.length; i++){
var regex = new RegExp(highlightWords[i],'ig');
data= data.replace( regex, '<span class="red">'+ highlightWords[i] +'</span>');
}
$('div').html( data );
jsBin demo 2 all line highlight
var words = ['Conflict discovered', 'Syntax error', 'Strange'];
var data_array=data.split('<BR>');
for(n=0;n<words.length;n++){
for(i=0; i<data_array.length; i++){
if (data_array[i].indexOf( words[n] ) >= 0){
data_array[i]="<span class='red'>"+data_array[i]+"</span>";
}
}
data = data_array.join('<BR>');
}
$('div').html( data );
data_array=data.split('<BR>');
for(var i=0, len=data_array.length; i < len; i++){
var dai = data_array[i];
if (dai.indexOf('Conflict discovered') >= 0 || dai.indexOf('Syntax error') >= 0){
data_array[i] = "<span class='red'>"+dai+"</span>";
}
}
data=data_array.join('<BR>');

getting the name of the element that is checked in checkbox

I have an html table which is dynamically created. The number of rows and coloumns wil be different for each search depending on search results.. This is how im creating a table
for(count = 0 ; count < facetList.length ;){
facetsString+="<div id='test'>";
facetsString+="<table id='facetTable' border='1' width='830px' style='margin-left:30px; margin-top:30px; font-family:Tahoma; '>";
for( var i=0 ; i< 6 && count < facetList.length ; i++ ){
facetsString+="<tr>";
for(var j=0;j<4 && count < facetList.length ; j++){
facetsString+="<td><form><input type='checkbox'></form> "+facetList[count].term+ "(" + facetList[count].count + ")" + "</td>";
count++;
}
facetsString+="</tr>";
}
facetsString+="</table>";
facetsString+="</div>";
}
return facetsString;
};
Now there is checkbox before each entry in the table..I want to display the name of the element whose box is checked...
This is the code that wrked.
function checkCount()
{
var allVals = new Array();
var newVals = new Array();
$('#panel :input[type=checkbox]:checked').each(function()
{
$("#slctFacet").empty();
newVals.push($(this).parent().text());
allVals.push($(this).val());
});
//alert(allVals);
// alert(newVals);
var fctArrayLength=newVals.length;
//alert(fctArrayLength);
if(fctArrayLength==0)
{
$("#slctFacet").empty();
}
else
{
for(var i=0;i<fctArrayLength;i++)
{
$("#slctFacet").append(newVals[i]);
}
}
}
$(":checkbox").click(checkCount);
};
// Get the form from its name
var form = document.forms.formName,
// Prepare an array to get the values
vals = []
// For each element in the form
[].forEach.call( form.elements, function ( el ) {
// Check if it's a checkbox. If it is, check if it's checked
if ( el.type === 'checkbox' && el.checked === true ) {
// Add the value to the "vals" array
vals.push( el.value )
}
} )
// Now all the values are available in the "vals" array
console.log( vals )

Categories