Can a javascript attribute value be determined by a manual url parameter? - javascript

I am trying to display data from an external .jsp file, which is set up something like this:
<tag>
<innertag1 id="1">
<innertag1 id="2">
</tag>
<tag>
<innertag2 id="3">
<innertag2 id="4">
</tag>
To display only information from only one particular "innertag" tag, I'm currently using:
NodeList labs = XMLInfo.getElementsByTagName("innertag1");
I'd like to be able to isolate any particular tag with ease. Theoretically, I could create many individual pages and simply change the values to "innertag2," "innertag3," etc., but this is obviously a bit impractical.
Is there a way to determine the value via a URL parameter? For instance, if I wanted to only display data from "innertag2," is there a way that the url http://www.server.com/data.jsp?id=innertag2 would adjust the tagname properly?
Thank you, any help would be much appreciated.

You can parse document.location.href and extract parameters from there. This is from an old HTML file where I used this technique (not sure if it's compatible on all browsers, however).
var args = {};
function parseArgs()
{
var aa = document.location.href;
if (aa.indexOf("?") != -1)
{
aa = aa.split("?")[1].split("&");
for (var i=0; i<aa.length; i++)
{
var s = aa[i];
var j = s.indexOf("=");
if (j != -1)
{
var name = s.substr(0, j);
var value = s.substr(j + 1);
args[name] = value;
}
}
}
}

Not sure if this is what you're looking for, but you can access parameters from the url using location.search.
6502's answer is almost good enough, it's not url decoding parameters. The function below is a bit more polished (descriptive variable names, no global variables)
function getUrlParams() {
var paramMap = {};
if (location.search.length == 0) {
return paramMap;
}
var parts = location.search.substring(1).split("&");
for (var i = 0; i < parts.length; i ++) {
var component = parts[i].split("=");
paramMap [decodeURIComponent(component[0])] = decodeURIComponent(component[1]);
}
return paramMap;
}
Then you could do
var params = getUrlParams();
XMLInfo.getElementsByTagName(params['id']); // or params.id

Related

Getting query string parameters from clean/SEO friendly URLs with JavaScript

I've recently switched my site to use clean/SEO-friendly URLs which has now caused me some issues with a JavaScript function I had for grabbing the query string parameters.
Previously I had been using this function:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
return (false);
}
Which worked fine on things like this as you could just call getQueryVariable("image") and return "awesome.jpg".
I've been playing with the indexOf(); function to try and grab the relevant parameters from the current URL, eg:
var url = window.location.pathname;
var isPage = url.indexOf("page") + 1;
In an attempt to get the array index number of the "page" parameter, and then plus 1 it to move along to the value of that (?page=name > /page/name/)
JavaScript isn't my main language, so I'm not used to working with arrays etc and my attempt to turn this into a new function has been giving me headaches.
Any pointers?
How about something like this? It splits the path and keeps shifting off the first element of the array as it determines key/value pairs.
function getPathVariable(variable) {
var path = location.pathname;
// just for the demo, lets pretend the path is this...
path = '/images/awesome.jpg/page/about';
// ^-- take this line out for your own version.
var parts = path.substr(1).split('/'), value;
while(parts.length) {
if (parts.shift() === variable) value = parts.shift();
else parts.shift();
}
return value;
}
console.log(getPathVariable('page'));
This can be done formally using a library such as router.js, but I would go for simple string manipulation:
const parts = '/users/bob'.split('/')
const name = parts[parts.length - 1] // 'bob'

InDesign Target XML Structure element by partial name

In my Structure pane there are some elements that their partial name is identical, eg. image01, image03, image03 etc.
I want to know if there is a way to access them via scripting using the itemByName() method, but by providing a partial name, like in CSS i can use
h1[rel*="external"]
Is there a similar way to do this in:
var items2 = items.xmlElements.itemByName("image");
You could try something like the code below. You can test against the markupTag.name properties with a regular expression. The regex is equivalent to something like /^image/ in your example (find image at the beginning of a string).
function itemsWithPartialName(item, partialName) {
var elems = item.xmlElements;
var result = [];
for (var i=0; i<elems.length; i++) {
var elem = elems[i];
var elemName = elem.markupTag.name;
var regex = new RegExp("^" + partialName);
if (regex.test(elemName)) {
result.push(elem);
}
}
return result;
}
itemsWithPartialName(/* some xml item */, 'image');
You can use an XPath:
var rootXE = app.activeDocument.xmlElements.item(0);
var tagXEs = rootXE.evaluateXPathExpression("//*[starts-with(local-name(),'image')]");

Assign new value to variable using itself

This doesn't work but I can't see why it wouldn't? any help people? :)
params = qs.split("=", 2),
id = params[1];
if(id.indexOf("?") != -1){
id = id.split("?", 1);
}
basically I want to change the value of 'ID' if the IF statement is true, if not.. it skips it and the value Id remains the default.
Thanks
The result of id = id.split("?", 1) is an array (of at most 1 item), but I think you want id to be a string. That would explain why id is not a string like you want.
I agree with the other comments. Please show us the URL string you want to parse and tell us which piece you're trying to get. Usually, you look for ? first, separate after that and then divide up various key=value sections.
If you had a URL like this:
http://www.example.com?foo=bar
Here's a simple function that gets you all the query parameters into an object:
function getParms(url) {
var sections, key, pieces = url.split("?");
var results = {};
if (pieces.length > 1) {
sections = pieces[1].split("&");
for (var i = 0; i < sections.length; i++) {
key = sections[i].split("=");
results[key[0]] = key[1];
}
}
return(results);
}
Working demo: http://jsfiddle.net/jfriend00/kNG3u/

Pull a Specific File name from URL with JavaScript/Jquery

Im trying to pull a specific file name from a URL, Ive looked at the posts but there isnt anything that answers the question that I need. I need a Javascript or Jquery that can pull just the file name ("Test1") from:
http://sharepoint/sites/Jarrod/DurangoTest/SitePages/Home.aspx?RootFolder=%2Fsites%2FJarrod%2FDurangoTest%2FShared%20Documents%2FTest1&FolderCTID=0x01200094D5A58A4F099E49BE1A8BA2F7DE9E0D&View={653454F3-1CE4-48C1-967C-5BA6023D349E}
You can get url information like that from the window.location object. Try this out
params = window.location.search.split(/&/)
for (var i=0; i < params.length; i++) {
if (params[i].match(/^\??RootFolder=/)){
paths = params[i].split(/\//);
filename = paths[paths.length-1];
break;
}
};
#Jonathan is on the right track. It looks like you're looking to parse a value from the querystring rather than find the name of the requested file. You'll first need to get the value from the querystring. You can use window.location.search to get the full querystring from the URL. Then parse the querystring to find the value you want. Here's a little JS function that does that:
// parses the query string provided and returns the value
function GetQueryVariable(query, name) {
if (query.indexOf("?") == 0) { query = query.substr(1); }
var pairs = query.split("&");
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split("=");
if (pair[0] == name) {
return pair[1];
}
}
return "";
}
Then you're ready to parse the value using Jonathan's suggestion to get the name of the file. You might have to do some unescaping (using the JS method unescape) to convert the value from the querystring into the "real" value that can be parsed more easily.

Get value of JSON object with inner objects by HTML form field name without eval

I have a problem like this Convert an HTML form field to a JSON object with inner objects but in to the other direction.
This is the JSON Object response from the server:
{
company : "ACME, INC.",
contact : {
firstname : "Daffy",
lastname : "Duck"
}
}
And this is the HTML form:
<form id="myform">
Company: <input type="text" name="company" />
First Name: <input type="text" name="contact.firstname" />
Last Name: <input type="text" name="contact.lastname" />
</form>
And this is the (pseudo)code:
var aFormFields;
for (var i = 0, iMax = aFormFields.length; i < iMax; i++) {
var sFieldName = aFormFields[i].getAttribute('name');
eval("sFieldValue = oResponse."+sFieldName);
}
Ok my solution works, but i looking for a good way to remove the evil eval from the code.
And the solution should also work for form fields with any count of dots in the field name.
Instead of:
eval("sFieldValue = oResponse."+sFieldName);
Use for single dotted fields:
sFieldValue = oResponse[sFieldName];
This will retrieve the value via its key.
Now if you need more than that you need to do the following:
Split sFieldName on .
Loop over that array and go down in oResponse till you reach the value that you desire
Code could look like this:
var node = oResponse, parts = sFieldName.split('.');
while(parts.length > 0) {
node = node[parts.shift()];
}
// node will now have the desired value
Further information on "Member Operators":
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Member_Operators
This works for a single property:
sFieldValue = oResponse[sFieldName]
But it won't work for nested data like contact.firstname.
For that, split the name by dots, and use loop through each name:
var aFormFields;
for (var i = 0, iMax = aFormFields.length; i < iMax; i++) {
var aFieldNameParts = aFormFields[i].getAttribute('name').split(".");
var oFieldValue = oResponse;
for(var j=0; j<aFieldNameParts.length; j++) {
oFieldValue = oFieldValue[aFieldNameParts[j]];
}
var sFieldValue = oFieldValue;
}
Note: if a property does not exist, an error will occur. You might want to check whether oFieldValue[ aFieldNameParts[j] ] exists or not.
While it is possible, I wouldn't loop over the input fields, but over the JSON object:
function fillForm (form, data, prefix) {
prefix = prefix ? prefix + "." : "";
for (var x in data) {
if (typeof data[x] === "string") {
var input = form.elements[prefix + x];
if (input)
input.value = data[x];
} else
fillForm(form, data[x], prefix + x);
}
}
fillForm(document.getElementById("myform"), oResponse);
(untested)
Assuming your naming scheme is consistent, you can convert the dot-notation into subscripts. You'd have to split the field name on the period and iterate or recurse over the tokens, converting each into a subscript. Of course this assumes that oResponse always contains a value for every field.
for (var i = 0; i < aFormFields.length; i++) {
var sFieldName = aFormFields[i].getAttribute('name');
var tokens = sFieldName.split('.');
var cur = oResponse;
for (var j = 0; j < tokens.length; j++) {
cur = cur[tokens[j]];
}
sFieldValue = cur;
}
please treat this as a combination of answer and question :)
i am currently trying to get my server to jsonify the data that i get sent from a form just like you...
in my case the form will in the end create a json object with multiple subobjects that can have subobjects which can have... as well.
the depth is up to the user so i should be able to support infinite recursion.
my "solution" so far just feels wrong, but it correctly does the job,
the function getRequestBody gets fed a req.body object from expressjs,
this is basically an object with the following mapping:
{
"ridic-ulously-deep-subobject": "value",
"ridic-ulously-deep-subobject2": "value",
"ridic-ulously-deep2-subobject3": "value",
}
the following html is in use:
<form>
<input name="ridic-ulously-long-class-string" value="my value" />
</form>
and the javascript function (that should work genericly, feed it a req.body object like above and it will return a json object):
function getRequestBody(reqB){
var reqBody = {};
for(var keys in reqB) {
var keyArr = keys.split('-');
switch(keyArr.length){
case 1:
if(!reqBody[keyArr[0]]) reqBody[keyArr[0]] = {};
reqBody[keyArr[0]] = reqB[keys];
break;
case 2:
if(!reqBody[keyArr[0]]) reqBody[keyArr[0]] = {};
if(!reqBody[keyArr[0]][keyArr[1]]) reqBody[keyArr[0]][keyArr[1]] = {};
reqBody[keyArr[0]][keyArr[1]] = reqB[keys];
break;
case 3:
if(!reqBody[keyArr[0]]) reqBody[keyArr[0]] = {};
if(!reqBody[keyArr[0]][keyArr[1]]) reqBody[keyArr[0]][keyArr[1]] = {};
if(!reqBody[keyArr[0]][keyArr[1]][keyArr[2]]) reqBody[keyArr[0]][keyArr[1]][keyArr[2]] = {};
reqBody[keyArr[0]][keyArr[1]][keyArr[2]] = reqB[keys];
break;
case 4:
// ...
//and so on, always one line longer
}
return reqBody;
}
this just feels wrong and its only covering 5 levels of subobjects right now,
it might happen that an application has enough functionality to reach seven or even ten levels though.
this should be a common problem, but my search effort turned up nothing within 10 minutes,
which usually means that i am missing some keywords
or
that there is no viable solution [yet] (which i cant really imagine in this case).
is there someone out there who has imagination and logic sufficient enough to unspaghettify this or will i just have to expand this function with even more clutter to get me down to 10 possible sublevels?
i think that in the end it wont make a big difference performance wise,
but i would really like NOT to create this awful behemoth :D
have fun
jascha

Categories

Resources