HTML: How to show a list whose size is unknown in advance on a webpage? - html

I'm like to admit that my knowledge of HTML is very little.
Assume we have a button on our pagepage that calls a javascript function: check().
The check() function withdraws an array (contantly updated) of values, e.g. string, from a server. If each element of the array has a certain property, e.g. contain a letter "a", then it wants to print those strings on the webpage.
The upperbound of the array size retrieved from the server is known but we do not know in advance how many elements satisfies the condition checked by check().
Question how to print the elements found by check() on a HTML file (a webpage).
Let's assume javascrip is in the the HTLM file too.

With something like <div id="destination"></div> in the HTML as a placeholder, you can use JavaScript to loop through your array of items and insert each one into the HTML with:
document.getElementById('destination').innerHTML += '<p>' + myData + '</p>';

Related

How do I build a simple HTML form to construct a link from two form fields?

At work, one of the systems I use outputs voyage schedules. The URL for each voyage is constructed as the form address followed by ?voyageCode= followed by the voyage number, which is a two-letter route prefix and a three-digit voyage number.
Rather than use the standard form, which has a whole bunch of fields I never need to use, I want to build a simple page where I can just select the route and enter a voyage number.
In practical terms, I'm trying to build a form with the following:
A drop-down menu or set of radio buttons to select the two-letter route code;
A text field to enter the three-digit route code;
A button or link to combine those inputs into a link in the format [LINK]?voyageCode=[ROUTE CODE][VOYAGE NUMBER]
My HTML knowledge is pretty outdated, and I've never worked much with forms. Can anyone advise on how I can construct this?
Why don't you use a select tag for the dropdown and a classic input text for the route coude ?
Then for the link part, you should capture the click event on your button through onClick and then call a small function that'll basically do that :
function concatRouteCode(){
var select= document.getElementById("routeCodeLetters");
var routeCodeLetters = select.options[select.selectedIndex].value;
var routeCodeNumber = document.getElementById('routeCode').value;
return routeCodeLettres+routeCodeNumber;
}
If you really want to combine the codes into a single query parameter, you'll have to use Javascript to fetch the values of the two fields and change the location. You don't need Javascript if you put the values into separate parameters, as in ?routeCode=xx&voyageNumber=123. In that case you would just give the select element the attribute name=routeCode and the input field the attribute name=voyageNumber.
In case you want to go with the first approach, you'd have something like
document.getElementById("idOfSubmitButton").addEventListener("load", function() {
const routeCode = document.getElementById("idOfSelectElement").value;
const voyageNumber = document.getElementById("idOfInputField").value;
location.href = "base URL here" + "?voyageCode=" + routeCode + voyageNumber;
});

Using JSON.stringify but SSJS variant in XPages

for an application I am building an administration panel where a power user should be able to check the JSON structure of a selected object.
I would like to display the JSON object in a computed text field but display/format it nicely so it is better human readable, something similar as in pretty print.
Is there any function I could use in SSJS that results in something similar so I can use display json nicely in computed text / editable fields?
Use stringify's third parameter "space":
JSON.stringify(yourObject, null, ' ');
space
A String or Number object that's used to insert white
space into the output JSON string for readability purposes. If this is
a Number, it indicates the number of space characters to use as white
space; this number is capped at 10 if it's larger than that. Values
less than 1 indicate that no space should be used. If this is a
String, the string (or the first 10 characters of the string, if it's
longer than that) is used as white space. If this parameter is not
provided (or is null), no white space is used.
As XPages doesn't support JSON.stringify yet you can include JSON's definition as SSJS resource and use it.
As Knut points out, you can certainly add json2.js to XPages; I've previously used an implementation as Marky Roden's post outlines. This is probably the "safest" way of doing so, from the SSJS side of things.
It does ignore the included fromJson and toJson SSJS methods provided out of the box in XPages. While imperfect, they are functional, especially with the inclusion of Tommy Valand's fix snippet. Be advised, using Tommy's fix does wrap responses to ensure a proper JS object can be parsed by shoving an Array into an object with a values property for the array; so no direct pulling of an Array only.
Additionally, I believe it would be useful to point out that a bean, providing a convenience method or two as wrappers to use either the com.ibm.commons.util.io.json methods to abstract the conversion method, or switching in something like Google GSON, might be more powerful and unified, based on your style of development.
Knut, Eric, I came so far myself already.
function prettyPrint(id) {
var ugly = dojo.byId(id).value;
var obj = $.parseJSON( "[" + ugly + "]" );
var pretty = JSON.stringify(obj, undefined, 4);
dojo.byId(id).innerHTML = pretty;
}
and I call it e.g.
var name = x$('#{id:input-currentObjectCollectionFiltered}').attr("name");
prettyPrint(name);
I tried to make use the x$ function but was not able to make the ID dynamic there e.g.
var ugly = x$('#{id:" + id + "}').val();
not sure why. would be nicer if I just would call prettyPrint('input-currentObjectCollectionFiltered'); and the function would figure it out.
Instead of dojo.byId(id).value I tried:
var ugly=$("#" + id).val();
but things returns and undefined object: I thought jquery would be smarter to work with dynamic id's.
anyway stringify works just fine.

$_SERVER[QUERY_STRING] copying itself

This is the part of the code for paging(when you see page 1,page 2...at the bottom).The $_SERVER[QUERY_STRING] is used to copy what was searched on previous page so that page number 2 displays results for same query.
The problem is that on page 2 the "query string" is added with page number &page=2 so when you click for page 3 the $_SERVER[QUERY_STRING] copies the query(which i need to be copied,eg. ?search=salad)and the page number(which is unnecessary),it looks like this &page=2&page=3
Is there any good way to do this?...it would be nice if something could change only the number of page instead copying whole word.
<a href='$_SERVER[PHP_SELF]?$_SERVER[QUERY_STRING]?start=$back'><font face='Verdana' size='2'>PREV</font></a>
$query = http_build_query(array('page' => $num) + $_GET);
printf('Prev', $_SERVER['PHP_SELF'], $query);
This uses the $_GET array, which contains all the values of $_SERVER['QUERY_STRING'] in a neat array, "overwrites" the page value of that array, then re-assembles it into a URL-encoded query string.

Duplicate form navigation elements, HTML ID's

I have a table displaying results from a database, and I am adding some paging/navigation buttons to it, such as 'prev', 'next', etc. These are being constructed for now as submit input buttons that are wrapped with a form tag and some hidden inputs to pass the needed querystring values back to the page itself, which means each form and element in the form should have an ID attribute.
Now, I'd love to add the navigation to both the top and bottom of the table, so I've modularized the navigation generation into a single routine I call whenever needed. This of course leads to duplicate form and element IDs in the page when there is more than one navigation bar included.
I've thought of passing some 'count' parameter to the routine so that when generating the HTML it could append that value to the IDs, and there are other solutions, such as using a global counter (ugly), etc, but I thought I'd poll the crowd and see what others have done in this situation.
Thanks,
Paul
Of the solutions you have thought of thus far, I would suggest the tactic that you mention first in the last paragraph. Passing a query string variable and loading X number of records including the number passed (doing error checking of course to make sure that some sneaky user doesn't try to put random characters in the query string) would resolve your issue.
Another option (since you are obviously doing codebehind for loading from the DB) is to create a session variable and assign the value to that when the links are clicked and use it to generate the list.
For both instances, when the page loads you can take the current value being passed and add X (number of rows in results shown +1) and change the value passed by the links.
I recently made a paginator myself, but approached it in a totally different way. I used php to generate the numbers, and each number (page) had a tag with an href that was mywebsite.php?page=x. That way you can use a get method, grab the page number from the url, and loop through as many times as you want for the number of pages displayed.
As they say, there is more than one way to skin a cat. I prefer the url passing method because I can stay away from forms and ID's in their entirety, making it so that the paginator can go wherever I decide to slap it in (and however many times).
Here's a snapshot of how I went about generating it. Hope it gives you some ideas!
/*PAGE NUMBERS*/
// ceil rounds a decimal up to the next integer
$pages=ceil(($totalrows-1)/$tablesize); //we subtract 1 from total rows because it counts 0
//(int) typecasts the $pages variable, so that it is divisible by an integer (ceil makes it a float)
$pages=(int)$pages;
//displays all the pages with their links
//if page count is less than 7 (the full paginator), display all pages
if($pages<=7){
for($i=1;$i<=$pages;$i++){
print "<a class='pages";
//add class current_page if necessary
if($page==$i){print " current_page";}
print "' href='index.php?page=";
print $i. "'>"." $i</a> "." "." ";
}
//if page count is more than 7
}else{
//if page # is less than 4, display pages up to 7, so that there are always 7 pages available (makes the buttons not jump around)
if($page<=4){
for($i=1;$i<=7;$i++){
print "<a class='pages";
//add class current_page if necessary
if($page==$i){print " current_page";}
print "' href='index.php?page=";
print $i. "'>"." $i</a> "." "." ";
}
//if page # is less than 4 away from the end, display pages $pages-7
}elseif($page>=$pages-3){
for($i=$pages-6;$i<=$pages;$i++){
//8,9,10,11,12,13,14,15
print "<a class='pages";
//add class current_page if necessary
if($page==$i){print " current_page";}
print "' href='index.php?page=";
print $i. "'>"." $i</a> "." "." ";
}
//if it's in between the ends, do this
}else{
for($i=1;$i<$pages+1;$i++){
//limit the number of visible pages to 7
if(($i>=$page-3)&&($i<=$page+3)){
print "<a class='pages";
//add class current_page if necessary
if($page==$i){print " current_page";}
print "' href='index.php?page=";
print $i. "'>"." $i</a> "." "." ";
}
}
}
}
There might have been some confusion it seems over what I was looking for, but in a nutshell, a simple way to avoid the duplicate ID issue when using a form-based paging solution that can be displayed multiple times on the same page (above and below tabular data, for example). My solution is to model it after the PHPMyAdmin paging, in that I simply remove the IDs for the form elements for now and reference the data being passed via the name attribute, which allows for duplicates.

Get page selection including HTML?

I'm writing a Chrome Extension, and I was wondering if it was possible to get the selected text of a particular tab, including the underlying HTML? So if I select a link, it should also return the <a> tag.
I tried looking at the context menu event objects (yes, I'm using a context menu for this), and this is all that comes with the callback:
editable : false
menuItemId : 1
pageUrl : <the URL>
selectionText : <the selected text in plaintext formatting, not HTML>
It also returns a Tab object, but nothing in there was very useful, either.
So I'm kind of at a loss here. Is this even possible? If so, any ideas you might have would be great. Thanks! :)
Getting the selected text of a page is fairly easy, you can do something like
var text = window.getSelection().toString();
and you'll get a text representation of the currently selected text that you can pass from a content script to a background page or a popup.
Getting HTML content is a lot more difficult, mostly because the selection isn't always at a clean HTML boundary in the document (what if you only select a small part of a long link, or a few cells of a table for example). The most direct way to get all of the html associated with a selection is to reference commonAncestorContainer, which is a property on a selection range that corresponds with the deepest node which contains both the start and end of the selection. To get this, you'd do something like:
var selection = window.getSelection();
// Only works with a single range - add extra logic to
// iterate over more ranges if needed
var range = selection.getRangeAt(0);
var container = range.commonAncestorContainer;
var html = container.innerHTML
Of course, this will likely contain a lot of HTML that wasn't actually selected. It's possible that you could iterate through the children of the common ancestor and prune out anything that wasn't in the selection, but that's going to be a bit more involved and may not be necessary depending on what you're trying to do.
To show how to wrap this all up into an extension, I've written a short sample which you can reference:
http://github.com/kurrik/chrome-extensions/tree/master/contentscript-selection/
If you don't want all of the siblings, just the selected HTML, use range's other methods like .cloneContents() (to copy) or .extractContents() (to cut).
Here I use .cloneContents():
function getSelectedHTML() {
var range = window.getSelection().getRangeAt(0); // Get the selected range
var div = document.createElement("div");
div.appendChild(range.cloneContents()); // Get the document fragment from selected range
return div.innerHTML; // Return the actual HTML
}