By default JSF renders the HTML field id name dynamically. ID name is generated randomly in the format formname:id_some_random_number.
Because of this i cannot use document.getElementById("").
Is there any solution for this problem?
If all else fails, you can try giving the elements unique css classes and then accessing them via getElementsByClassName(). Or try browsing the childNodes() of an element with known id. Or you can add a node with known id inside your target element and then use .parentNode :)
You just need to specify the ID of the input.
However, note that the ID will be prefixed by the ID of the form that contains the input field.
For example:
<h:form id="myForm">
...
<h:inputText id="myInput" .../>
the real ID of the inputText is myForm:myInput.
Thus, this Javascript code will work:
var obj = document.getElementById("myForm:myInput");
Edit (for precision)
To be more precise, if a component implements the NamingContainer interface in Java, then all the nested components will have their ID prefixed by the ID of this component. This is the case for the <h:form/> component, but also for <h:datatable/>.
You can get the generated ID by using UIComponent.getClientId (JSF 2, if you can use it, adds a no-arg version that makes this more useful with EL expressions). See this blog post for tips on working with JSF component identifiers (though note the caveats).
Related
But the browser is only considering the first id, i have different buttons in my html file which will work as a pop up form.
Using the same id multiple times in a document is not allowed, and is invalid HTML. Look into using classes instead.
You should not use the same id on multiple elements. You could use the same class name and then set the event handler using the shared class instead of an id.
$(document).on('click', '.shared-class', function() {
// prompt your modal
});
When I do the web scraping, I notice amazon best seller pages have the same id for multiple elements, however, it also offers another unique id attribute for its child , I am guessing that if you have a unique id for each child element in one HTML file, it's ok to have some sort of shared id attribute for the parent, although this seems to be against CSS id rules.
You could use document.querySelectorAll
const allDivs = document.querySelectorAll("#buttons");
allDivs.forEach(div=>{
div.addEventListener(click,function(){})
})
I have two form on same page. There is a text field with same name in both of the forms.
I am tried to read the value of the text field from one of the two forms. if I am trying to read the value using below code i am getting the value . But I am not sure from which forms it is returning the value.
document.getElementById("groupId")
Now if I am trying to read the value from specific form using below code I am receiving the error.
document.forms["form1"].getElementById("groupId")
Please suggest whats wrong I am doing and how can we read the value of a control ?
I can use both javascript and jquery.
Since you're using jQuery you could do :
$('[name=form_name]').find('#field_id');
Your case e.g :
$('[name=form1]').find('#groupId');
Using pure js you could do it like :
document.form_name.getElementById("field_id");
Sample of your case :
document.form1.getElementById("groupId");
Hope this helps.
You can do the following with jquery.
var element = $(document.forms["form1"]).find('#groupId')
And to get the text value you can use the val function.
var text = element.val();
if i am trying to read the value using below code i am getting the value . But i am not sure from which forms it is returning the value.
This means you have multiple elements with same id which is a big NO. id's are supposed to be unique in your entire HTML. If for some reason you want to use same id on multiple elements to work with JavaScript be aware the same task is possible by assigning same class to the elements and accessing by class
Having said that, Change your HTML to not have duplicate id and change them to have a common class. Now with this structure you can access the element starting from your from like below
$('form[name="form1"]').find('input.ClassName').val()
Also for info purpose: If you have multiple elements with same id in your HTML and when you try to access by id the element which is placed in top parsing from top will be selected always.
The W3C standards for HTML require the id to be unique in a document.
I am wondering if the html class attribute should only be used for styling. Is there any drawback to using the class attribute as a variable. The W3 spec http://www.w3.org/TR/html5/dom.html#classes does not specify one way or another but, all examples and training point in the direction of styling only for multiple objects.
In my case I want to use the class attribute as variable that matches the key value in a object array. For example in my Javascript code I have an object that has a number of key/value pairs. On my web app I have a number of save buttons. When a save button is clicked I grab the parents class attribute value and use it as the key for the object to know which value to change. The class attribute on the parent has not other value than to let me know which key value pair to change in my object
While I'm sure it's possible to use classes that way, it's certainly not their intended purpose. html has data attributes that provide the functionality you want, for example
<button data-key="some value" name="" id="">click me</button>
You can then get that value (onClick if you like) and use it as a key for your object/data structure. Theres a good overview here
While it is not bad, it neither is best practice.
You can, instead of using the class attribute, define explicit data attributes. Using the class attribute would mean that you could not use several classes (because that would be a weird key to search for in an object, right?).
For instance:
<div class="any classes you like" data-mykey="searchforthiskey">
<button></button>
</div>
In jQuery:
$('button').click(function() {
var key = $(this).closest('div').attr('data-mykey');
});
From a functional perspective, there's no reason to NOT use the class attribute to store information about that element. You can access a class attribute as easily as you can a data attribute.
From a standards perspective, it is probably better to use a data attribute. Why? Well, if you are the only person working on your front-end, no big deal. If you are one of many on a team of front-end developers, who works specifically on the javascript side of things, you may run into a conflict with another front-end developer who works on the HTML/CSS side of things. They may remove a class from the element, not realizing that its also being used as your javascript hook into that element. In that case, you're better off creating your own data attribute, which then makes it clear that this attribute is probably data related and won't be molested by someone just trying to fix the styling of that element.
I run a music blog using WordPress and I have a custom music player for it. Every time a post has a song attached to it, I want to create a way to hold that information and later access custom variables. What I need is something along the lines of...
<div class="playable"
title="Song Title"
mp3="URL"
soundcloudLink="https://soundcloud.com/cashcash/take-me-home-jordy-dazz">
</div>
Then in my $(document).ready() function I would need a function that finds all objects of class "playable" and be able to access the title tag, mp3 tag, soundcloudLink tag, etc.
Any easy suggestions?
It sounds like you're looking for data-* attributes:
3.2.3.9 Embedding custom non-visible data with the data-* attributes
A custom data attribute is an attribute in no namespace whose name starts with the string "data-", has at least one character after the hyphen, is XML-compatible, and contains no uppercase ASCII letters.
All attribute names on HTML elements in HTML documents get ASCII-lowercased automatically, so the restriction on ASCII uppercase letters doesn't affect such documents.
Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.
These attributes are not intended for use by software that is independent of the site that uses the attributes.
E.g., they always pass validation, and they're only for your use.
So for instance:
<div class = "playable"
title = "Song Title"
data-mp3 = "URL"
data-soundcloudLink = "https://soundcloud.com/cashcash/take-me-home-jordy-dazz"
></div>
When you need to access that information, you get a jQuery object for the div, and then use attr("data-mp3") or data("mp3") to access it. (Or without jQuery, get the HTMLDivElement and use getAttribute.) Note that I haven't changed title. title is a valid attribute, and accessible via .prop("title") on jQuery instances or via .title on DOM elements.
Note that data is assymetrical: It reads from data-* attributes for initialization, but doesn't write to them.
You can try the data- attribute which can easily be retrieved by .data() method.
HTML:
<div id="thing" data-title="Keine Lust" data-file="keine_lust.mp3"></div>
JQuery
var song_title = $("#thing").data("title");
var song_file = $("#thing").data("file");
You can use the .hasClass() jquery function to display the attributes of the elements with that class. Add an ID to the element like in this case I added test.. here is how to alert them.
$(document).ready(function(){
var className = $('#test').hasClass('playable')
if( className ){
var url = $('#test').attr('soundcloudLink');
var title = $('#test').attr('title');
document.write(title);
document.write(url);
}
});
This one displays the soundcloud link and the title if the element has the class playable. here is a fiddle. http://jsfiddle.net/uprosoft/2Frk3/3/
I am using jsf and liferay. I am very new to it. For any javascript method which select any element of jsf for some javascript or jquery method I need to set it like.
<h:inputText id="abc" binding="#{abc}"/>
Please note that I have set binding same as id, somebody has told me to do like that. Without setting binding like that I was not able to select any element in my javascript method. I really dont know the reason. Since this was working for me so I have used it, without going in detail
But now for some functionality I really need actual use of binding, bind UIInput to managed bean. So I have changed my tag like.
<h:inputText id="abc" binding="#{mybean.uiAbc}"/>
In this case my javascript method like
function doSomething(){
$("##{abc.clientId}").val("hello everyone");
}
its not working. Its giving me exception like... # is undefined..
In javascript I have nothing to do with binding so why it stops working now? And why it was working earlier with same value of binding as id have?
If you replace binding="#{abc}" by binding="#{myBean.uiAbc}", then you should obviously also change #{abc.clientId} elsewhere in the view by #{myBean.uiAbc.clientId}.
function doSomething(){
$("##{myBean.uiAbc.clientId}").val("hello everyone");
}
That the id and binding need have to be the same name is complete nonsense.
The only problem which you may face is that the default JSF naming container separator character, :, is a special character in CSS selectors, like as used in jQuery, and thus this construct would possibly fail. This construct would only work if you've manually reconfigured your JSF webapp to use a different, CSS-safe, character like - or _. If you indeed use the default of :, then you should use
function doSomething(){
$("[id='#{myBean.uiAbc.clientId}']").val("hello everyone");
}
See also:
How to use JSF generated HTML element ID with colon ":" in CSS selectors?
Your myth for following is wrong, i.e. to have same id and binding attribute.
id="abc" binding="#{abc}"
JSF renders component with id which provided by us with preceding by form id. e.g. in your case it will be,
:formId:abc
to avoid prepending form id just set prependId attribute to false. it will render the component with id "abc" only.
Also if your component is naming container e.g. dataTable. Then you the method accessing client id is different.
In short just right click in your browser and check the element's id and you can find the id to the jQuery.