JSF ui:include and getElementById - javascript

I'm writing the ui:composition xhtml file to include in different pages using ui:include. It looks like there's no way I can refer to the tags from javascript in this file using getElementById, as the tag ids might be prepended with the form id from the parent page. Is there a workaround?
Found this answer after I posted the question. It helped!
Acquire full prefix for a component clientId inside naming containers with JSF 2.0

You could do this:
var elem = document.querySelector( '[id$="-test"]' );
where test is the ID without the prefix, and - is the prefix separator.
The above code will select the element which "id" attribute ends with "-test" (e.g. <div id="form1-test">...</div>).
Live demo: http://jsfiddle.net/8kyb2/
Note that querySelector() paired with an attribute-ends-with selector performs slower than getElementById().

If you happen to use Apache's Tomahawk Components, and specify forceId="true", tag ids will remain unchanged. E.g.:
<t:inputText id="name" forceId="true" value="#{myBean.property}" />
will result in an <input type="text" id="name" ... / >.

Related

How can I get value of checked JSF radiobutton using JS? [duplicate]

I am trying to implement jQuery with PrimeFaces and JSF components, but it's not working properly. When I tried to do the same with HTML tags it;s working properly.
Here is the code with HTML tags which works properly with jQuery:
<input type="checkbox" id="check2"></input>
<h:outputText value="Check the box, if your permanent address is as same as current address."></h:outputText>
<h:message for="checkbox" style="color:red" />
with
$("#check2").change(function() {
if ($("#check2").is(":checked")) {
$("#p2").hide();
} else {
$("#p2").show();
}
});
Here is the code with PrimeFaces/JSF which doesn't work properly with jQuery:
<p:selectManyCheckbox >
<f:selectItem itemLabel="1" value="one" id="rad" ></f:selectItem>
</p:selectManyCheckbox>
with
$("#rad").change(function() {
if ($("#rad:checked").val() == "one") {
$("#p2").hide();
} else {
$("#p2").show();
}
});
You should realize that jQuery works with the HTML DOM tree in the client side. jQuery doesn't work directly on JSF components as you've written in the JSF source code, but jQuery works directly with the HTML DOM tree which is generated by those JSF components. You need to open the page in webbrowser and rightclick and then View Source. You'll see that JSF prepends the ID of the generated HTML input elements with the IDs of all parent NamingContainer components (such as <h:form>, <h:dataTable>, etc) with : as default separator character. So for example
<h:form id="foo">
<p:selectManyCheckbox id="bar" />
...
will end up in generated HTML as
<form id="foo" name="foo">
<input type="checkbox" id="foo:bar" name="foo:bar" />
...
You need to select elements by exactly that ID instead. The : is however a special character in CSS identifiers representing a pseudo selector. To select an element with a : in the ID using CSS selectors in jQuery, you need to either escape it by backslash or to use the [id=...] attribute selector or just use the old getElementById():
var $element1 = $("#foo\\:bar");
// or
var $element2 = $("[id='foo:bar']");
// or
var $element3 = $(document.getElementById("foo:bar"));
If you see an autogenerated j_idXXX part in the ID where XXX represents an incremental number, then you must give the particular component a fixed ID, because the incremental number is dynamic and is subject to changes depending on component's physical position in the tree.
As an alternative, you can also just use a class name:
<x:someInputComponent styleClass="someClassName" />
which ends up in HTML as
<input type="..." class="someClassName" />
so that you can get it as
var $elements = $(".someClassName");
This allows for better abstraction and reusability. Surely those kind of elements are not unique. Only the main layout elements like header, menu, content and footer are really unique, but they are in turn usually not in a NamingContainer already.
As again another alternative, you could just pass the HTML DOM element itself into the function:
<x:someComponent onclick="someFunction(this)" />
function someFunction(element) {
var $element = $(element);
// ...
}
See also:
How can I know the id of a JSF component so I can use in Javascript
How to use JSF generated HTML element ID with colon ":" in CSS selectors?
By default, JSF generates unusable IDs, which are incompatible with the CSS part of web standards
Integrate JavaScript in JSF composite component, the clean way
You also can use the jQuery "Attribute Contains Selector" (here is the url http://api.jquery.com/attribute-contains-selector/)
For example If you have a
<p:spinner id="quantity" value="#{toBuyBean.quantityToAdd}" min="0"/>
and you want to do something on its object you can select it with
jQuery('input[id*="quantity"]')
and if you want to print its value you can do this
alert(jQuery('input[id*="quantity"]').val());
In order to know the real html tag of the element you can always look at the real html element (in this case spinner was translated into input) using firebug or ie developer tools or view source...
Daniel.
If you're using RichFaces you can check rich:jQuery comonent. It allows you to specify server side id for jQuery component. For example, you have component with specified server id, then you can apply any jQuery related stuff to in next way:
<rich:jQuery selector="#<server-side-component-id>" query="find('.some-child').removeProp('style')"/>
For more info, please check doumentation.
Hope it helps.
look this will help you when i select experience=Yes my dialoguebox which id is dlg3 is popup.and if value is No it will not open

How can I find CSS selector from a HTML matching a specific criteria?

I want to parse any given link and see if there are any CSS selectors whose attributes maybe partially or completely matching a specific keyword.
If my keyword is print, I want every CSS selector in the given link that has print anywhere in it, it maybe present at either the name, id or class or anywhere.
For example if the link I give gets me the following html:
<body>
<div>
<p class="testprintrandom">Lorem ipsum</p>
<p id="randomstackoverflowrandomtext">Lorem ipsum</p>
Good Bye
<input type="text" placeholder="Your Email address">
</div>
</body>
If my keyword is "print" then I should get the selector "p.testprintrandom" as a part of it's class name had print in it. similarly if my keyword is "stackoverflow" I should get the id "randomstackoverflowrandomtext" as a part of the id has stackoverflow inside it. similarly if my keyword is email then I should get the CSS selector for the input tag as the placholder had email in it.
First off I want to know if this is possible and if so how can I achieve this, is there any specific library or framework I can use?
I will later be using the obtained selectors with puppeteer if that should influence the answer in any way.
Just a example/sample:
According to your question that you want to find an element with respect to its css matching selector see this:
suppose that i have a button with css = class="lx-stream-show-more__button gel-long-primer-bold"and i want to get the element matching with gel-long-primer-boldas in the end of css so i would do this:
from selenium import webdriver
browser = webdriver.Chrome()
browser.get(url)
bt = browser.find_elements_by_css_selector('.gel-long-primer-bold')
here in bt i will get all elements that ends matching with gel-long-primer-bold css in it. Then will perform further actions.
Note: It is just a example to give you idea. You will get better answer if you provide your code or provide better explanation to your question.
Hope this will help you! :)

Can't pull input-field value located beyond form tag

Problem
I use popup calendar, which is launched via href. I need to pass 'document.tstest.timestamp' (date input field) parameter into javascript function. And all worked well, BUT:
I want to include this tag-file into another form, so I can't use form
<form name="tstest">
in my tag file. As a result, without form I can't find document.timestamp input-field (as I understand due window.object hierarchy)
My tag file:
<form name="tstest">
<input type="Text" id="time_stamp" name="timestamp">
<a href="javascript:show_calendar('document.tstest.timestamp',
document.tstest.timestamp.value);"> showCalendar</a>
</form>
<script>
function show_calendar(target, value) {
............
}
</script>
Help me, please, to find out solution.
Your element has an id attribute on it so you can just use document.getElementById() to get a reference to it. I'd suggest modifying your show_calendar function to either take the id or a reference to the element directly, though, since you'll likely need to reference it again inside of that function.
You should be able to do the following anywhere on the page and get the element:
var elem = document.getElementById("time_stamp");
var myVal = elem.value;
This would work too
<a href="javascript:show_calendar('document.tstest.timestamp',
document.getElementById('time_stamp').value);"> showCalendar</a>
Don't use document.tstest as syntax instead use document.getElementById("time_stamp")
Also remember an id is unique so don't put 2 elements with a same I'd on a same page

JavaScript variable name and HTML input name attribute: namespace collision?

In an HTML file I have the following:
<input type="..." name="myInput1" />
In a corresponding JS file I have the following variable which will hold the string value of that input after blur:
var myInput1;
Is there any problem in having these two identical names? I'm guessing that the namespaces are separate so it is ok.
Short answer, no problem whatsoever.
A short answer is, indeed, no. However, it also greatly depends on how you use the variable. Let's consider that you use javascript for validating that the variable is set as follows:
if(myInput1) {do something}
If you also decide to set the id to be the same as the name is as follows (cause you didn't specify that, it can be anything):
<input type="myInput1" name="myInput1" />
your variable myInput1 will be set to contain the DOM element and won't be empty anymore.
This link between JS and HTML is not only interesting but can be used to create an exploit as described in the section 3.1.2 of Postcards from the post-XSS world (that's where I have the idea from - and yes, it still works even though the article is from 2011).

Best way to store JQuery variables?

I just want to get some thoughts on storing variables for JQuery's use.
Example
Here JQuery would use the the value of the video_id hidden input, and then voteup the video by the video_id.
<form class='voteup' action='' method='post'>
<input type="hidden" name='video_id' value='<?php echo $video_id; ?>' />
<input type='submit' value='Vote Up' />
</form>
Note: This is just an example.
But what if I want a link to do the same thing. Where would I store the video_id?
Obviously, I could store the video_id in the class attribute, but I don't think that this is the best way, especially if I needed to send more than one variable.
Any ideas on this?
I must mention that I'm only looking for XHTML valid ways.
You can use the jQuery data method to attach arbitrary data to an element. In your case, if I've understood what you're trying to do correctly, you probably want to do something like this:
$(document).ready(function() {
$("#yourLink").data("video_id", "<?php echo $video_id; ?>");
});
As you are looking for valid XHTML solutions, you can't use the HTML5 data-* attributes. If that was the case, you could add the attribute value directly on the element (as you've done with the value attribute in your example).
The data method does not require a corresponding data-* attribute to be present on the element, so this will still allow you to write valid XHTML.
If you digg HTML5 you should go for the data attribute.
http://ejohn.org/blog/html-5-data-attributes/
In an HTML 5 page, you can use "data-" attributes for things like that:
<img src='http://placekitten.com/100/100' data-video-id='whatever'>
Then, from jQuery:
$('img').click(function() {
var video = $(this).data('video-id'); // 'videoId' also works here
});
If you're (tragically) stuck with strict XHTML, well, you're stuck. For an <a> tag you could possibly use the "rel" attribute I guess. In general "class" is probably in fact the thing to do. The convention I've used for name-value pairs in the "class" is to separate them with a colon and then extract them via regex:
<sometag class='whatever videoId:video22 something'>
and then:
$('sometag').click(function() {
var videoId = this.className.replace(/videoId:(\S*)/, '$1');
// ...
});
Perhaps use the rel attribute, and grab it in jQuery using the .attr() method.
var myVar = $('#link_id').attr('rel');
http://api.jquery.com/attr/

Categories