Use dynamic element ID in #{rich:clientId()} function - javascript

We can get element by static ID using rich:clientId() function as follows
document.getElementById('#{rich:clientId(JSF_ID)}').click();
However, I need to use a dynamic ID which takes the form of var + "_ID" where var can be employee, student, etc and thus resulting in employee_ID, student_ID as actual ID.
I tried as follows:
dynamicID = var + '_ID';
document.getElementById('#{rich:clientId(dynamicID)}').click();
However, it didn't work. How can I achieve this?

It looks like you are setting dynamicID via JavaScript, am I right?
If yes, the EL-expression #{rich:clientId(dynamicID)} cannot be evaluated as EL on the server during the rendering of the page since the dynamicID is only available on the client (=browser) when the page has already been built up on the server and sent to the browser.
Where does var come from? How is it applied to the component with the dynamicID? Can't you use the same approach for the getElementById?

For concatenating a variable with a constant in JSF on server-side, see the following already answered post Concatenate strings in JSF/JSP EL and Javascript. Basically it gives you a how-to in creation of an own concatenation function for jsp/jsf. Works pretty need.
As a hint: you can use #{rich:element(JSF_ID)} instead of document.getElementById('#{rich:clientId(JSF_ID)}') to keep the source readeable - it will render identical results.
Good luck...

Related

How to get element from HTML stored in variable

I am running an API to retrieve email from external system. I managed to get HTML code from the returned JSON and store it in a variable. Now, I would like to run some further operations on this HTML - for example get all elements with
[data-type="whatever"].
It would be easy in html document:
var x = document.querySelectorAll('[data-type="whatever"]');
However the HTML document I want to work with is stored in the variable so the code I write in API does not recognise it as a document. How can I do it? Any suggestions with vanilla JS?
You can try something like this.
let rawDoc = '<html><head><title>Working with elements</title></head><body><div id="div1">The text above has been created dynamically.</div></body></html>'
let doc = document.createElement('html');
doc.innerHTML = rawDoc;
let div1 = doc.querySelector('#div1');
console.log(div1)
What if you use innerHTML? or maybe I don't fully understand the question.
Since you are working without a document you have 2 options.
1. Use regex to get what you need (something like /<.+>.+ data-type="whatever".+<\/.+>/gi) should do (but for an exact match you may need to make something better).
2. Insert the html in a hidden part of the dom and select what you need from it (like in Zohir answer - he provided a good example).
I used following code with angular to store whole html content in a variable and pass it as argument to call API.
var htmlBody = $('<div/>').append($('#htmlBody').clone()).html();
This might work for you as i was working on sending email to pass invoice template so try this.

Find text in source code of page and create hyperlink

I need to use JavaScript to search the source code of the current page for a string, e.g data-userId="2008", then extracts the id number (2008 in this case) and creates a hyperlink to include it, e.g. http://www.google.com?2008.
I've been attempting to use indexOf and document.documentElement.innerHTML approaches but not getting anywhere. I've got closer with the help of this post but no success yet.
Here's what i have so far:
<script type="text/javascript">
function getVals() {
code = document.getElementsByTagName("html")[0].innerHTML;
results = code.match(/data-userId=(\d*)&/g);
for (i=0;i<results.length;i++) {
value = results[i].match(/data-userId=(\d*)&/);
}
}
onload = getVals;
document.write(code);
</script>
Due to restrictions on our network the solution needs to be JavaScript.
Use the getAttribute() method of the Element object http://www.w3schools.com/jsref/met_element_getattribute.asp.
I'm not sure why exactly you'd query the html element and then look at innerHTML. Do you not know which tags/selectors will contain the data attribute you're looking for? If you don't know which selectors you're looking for you can use a recursive function like this to walk the DOM and store the values in a data structure of your choice - I'll use an array of objects in this example (not sure how you need this data formatted).
Also, I'm not sure how you're choosing to visit these pages, but the below code could be easily modified to create hyperlinks when/if the attributes you're looking for are found.
var storeElements = [];
function walkTheDOM(node){
if(node.getAttribute('data-userId') !== null){
storeElements.push({"element": node, "attrValue": node.getAttribute('data-userId'});
}
node = node.firstChild;
while(node){
walkTheDOM(node);
node = node.nextSibling;
}
}
Then you can call the function like this:
walkTheDOM(document.querySelectorAll('html')[0]);
If this isn't what you're looking for let me know and I can change my answer. For those of you who've read Douglas Crockford's "Javascript: The Good Parts" this function may look very familiar :).

HTML Append Variable to Query String

I have http://localhost/?val=1
When I click on a link, is there a way this link can append a query variable to the current string, for example:
Link
so when I click it the url would be:
http://localhost/?val=1&var2=2
but when I click the link it removes the first query string and looks like
http://localhost/&var2=2
Is such a thing possible with normal HTML?
You can't do that using only html, but you can do it with js or php:
Using JS:
<a onclick="window.location+=((window.location.href.indexOf('?')+1)?'':'?')+'&var2=2'">Link</a>
Using Php:
Link
Notice 1: make sure you don't have the new variable in the current link, or it'll be a loop of the same variable
Notice 2: this is not a professional way, but it could work if you need something fast.
Basically you want to get your current URL via JavaScript with:
var existingUrl = window.location.href; // http://localhost/?val=1
Then append any Query Strings that are applicable using:
window.location.href = existingUrl + '&var2=2';
or some other similar code. Take a look at this post about Query Parameters.
Note: A link would already have to exist with an OnClick event that calls a function with the above code in it for it to work appropriately.
Now obviously this isn't very useful information on it's own, so you are going to want to do some work either in JavaScript or in Server code (through use of NodeJS, PHP, or some other server-side language) to pass those variable names and their values down so that the button can do what you are wanting it to do.
You will have to have some logic to make sure the query parameters are put in the URL correctly though. I.E. if there is only one query param it's going to look like '?var1=1' and if it's any subsequent parameter it's going to look like '&var#=#'.

Can a variable be passed as an element id in javascript

I'm trying to get some AJAX running with Django using jQuery. The problem is that the ID of the element I'm trying to change isn't set in stone, it's a Django template variable so it is different for each element in the table, but I want to use AJAX to change that element. I'm passing the dictionary from a Django view to JavaScript via simplejson, the pertinent objects being ID and model (not real variable names, just wanted to make it obvious what I am trying to do). Some pseudo code (third line, wrote it like python because I don't know how to do this in JavaScript):
var quantity_update = function(msg, elem) {
var response_obj = eval('(' + msg + ')');
var newtotal = document.getElementById("%s, %s"); % (response_obj.id, response_obj.model)
subtotal.innerHTML = "<td>"+response_obj.subtotal+"</td>";
Is something like this possible, and if so how?
Javascript doesn't have fancy string formatting (%s), but you can use plain string concatenation, just like you can in Python:
var id = response_obj.id + ', ' + resonse_obj.model
You don't need to worry about the string being generated dinamically. It is still a string after all and getElementById accepts it the same way .
You probably shouldn't be doing the eval() yourself to parse the JSON. I'm pretty sure you can have JQuery do that for you when you do the AJAX request.
If your element ID is not set in stone, you might want to identify the element using other means. Many JS framework such as jQuery supports identification via CSS Selector. For example you can identify the element you want to change by combination of its tag and class.
For documentation on the available selector you should read jQuery Selector Documentation
You can totally pass jquery css selectors as variables. Simple example:
var elementId = $('td').eq(0).attr('id'),
myElement = $('#'+elementId);
In this example, we grab the ID of the first TD in your document, find its id, and use that to get "myElement"
You may find it helpful to review the "selectors" section of the jQuery documentation (api.jquery.com) to review all your options for finding an element. In my example I also am using the jquery.eq() method, which filters a list of selectors (in this case all the TDs) to a specific one.

What is common AJAX convention for knowing a particular state when a page is loaded?

This has been a question I've had since I started doing serious ajax stuff. Let me just give an example.
Let's say you pull a regular HTML page of a customer from the server. The url can look like this:
/myapp/customer/54
After the page is rendered, you want to provide ajax functionality that acts on this customer. In order to do this, you need to send the id "54" back to the server in each request.
Which is the best/most common way to do this? I find myself putting this in hidden form forms. I find it easy to select, but it also feels a bit fragile. What if the document changes and the script doesn't work? What if that id gets duplicated for css purposes 3 months from now, and thus breaks the page since there are 2 ids with the same name?
I could parse the url to get the value "54". Is that approach better? It would work for simple cases repeatedly. It might not work so well for complex cases where you might want to pass multiple ids, or lists of ids.
I'd just like to know a best practice - something robust that is clean, elegant and is given 2-thumbs up.
I think the best way to do this is to think like you don't have Ajax.
Let's say you have a form which is submitted using Ajax. How do you know what URL to send it to?
The src attribute. Simply have your script send the form itself. All the data is in the form already.
Let's say you have a link which loads some new data. How do you know the URL and parameters?
The href attribute. Simply have the script read the URL.
So basically you would always read the URL/data from the element being acted upon, similar to what the browser does.
Since your server-side code knows the ID's etc. when the page is being loaded, you can easily generate these URLs there. The client-side code will only need to read the attributes.
This approach has more than just one benefit:
It makes it simpler where the URLs and data is stored, because they are put exactly in the attributes that you'd normally find then in HTML.
It makes it easier to make your code work without JavaScript if you want to, because the URLs and all are already in places where the browser can understand them without JS.
If you're doing something more complex than links/forms
In a case where you need to allow more complex interactions, you can store the IDs or other relevant data in attributes. HTML5 provides the data-* attributes for this purpose - I would suggest you use these even if you're not doing HTML5:
<div data-article-id="5">...</div>
If you have a more full-featured application on the page, you could also consider simply storing your ID in JS code. When you generate the markup in the PHP end, simply include a snippet in the markup which assigns the ID to a variable or calls a function or whatever you decide is best.
Ideally your form should work without javascript, so you probably have a hidden form input or something that contains the id value already. If not, you probably should.
It's all "fragile" in the sense that a small change will affect everything, not much you can do about that, but you don't always want to put it in the user's hands by reading the url or query string, which can be easily manipulated by the user. (this is fine for urls of course, but not for everything. Same rules that apply to trusting $_GET and query strings apply here).
Personally, I like to build all AJAX on top of existing, functional code and I've never had a problem "hooking" into what is already there.
Not everything is a form though. For
example, let's say you click a "title"
and it becomes editable. You edit it,
press enter, and then it becomes
uneditable and part of the page again.
You needed to send an ID as part of
this. Also, what about moving things
around and you want those positions
updated? Here's another case where
using the form doesn't work because it
doesn't exist.
All of that is still possible, and not entirely difficult to do without javascript, so a form could work in either case, but I do indeed see what you're saying. In almost every case, there is some sort of unique id, whether it's a database id or file name, that can be used as the "id" attribute of the html that represents it. * Or the data- attribute as Jani Hartikainen has mentioned.
For instance, I have a template system that allows drag/drop of blocks of content. Every block has an id and every area that it can get dropped has one as well. I will use prefixes on the containing div id like "template-area_35" or "content-block_264". In this case, I don't bother to fallback w/o javascript, but it could be done (dropdown-> move this to area for example). In any case, it's a good use of the id attribute.
What if that id gets duplicated for
css purposes 3 months from now, and
thus breaks the page since there are 2
ids with the same name?
If that happens (which it really shouldn't), someone is doing something wrong. It would be their fault if the code failed to work, and they would be responsible. Ids are by definition supposed to be unique.
IMHO putting is at a request parameter (i. e. ?customerId=54) would be good 'cos even if you can't handle AJAX (like in some old mobile browsers, command-line browsers and so) you can still have a reference to the link.
Apparently you have an application that is aware of the entity "Customer", you should reflect this in your Javascript (or PHP, but since you're doing ajax I would put it in Javascript).
Instead of handmaking each ajax call you could wrap it into more domain aware functions:
Old scenario:
var customer_id = fetch_from_url(); // or whatever
ajax("dosomething", { "customer": customer_id }, function () {
alert("did something!");
});
ajax("dosomethingelse", { "customer": customer_id }, function () {
alert("did something else!");
});
New scenario:
var create_customer = function (customer_id) {
return {
"dosomething" : function () {
ajax("dosomething", { "customer": customer_id }, function () {
alert("did something!");
});
},
"dosomethingelse": function () {
ajax("dosomethingelse", { "customer": customer_id }, function () {
alert("did something else!");
});
}
};
}
var customer_id = fetch_from_url(); // or whatever
var customer = create_customer(customer_id);
// now you have a reference to the customer, you are no longer working with ids
// but with actual entities (or classes or objects or whathaveyou)
customer.dosomething();
customer.dosomethingelse();
To round it up. Yes, you need to send the customer id for each request but I would wrap it in Javascript in proper objects.

Categories

Resources