How can I know the id of a JSF component so I can use in Javascript

前端 未结 6 1403
北海茫月
北海茫月 2020-11-22 02:47

Problem: Sometimes you will want to access a component from javascript with getElementById, but id\'s are generated dynamically in JSF, so you

6条回答
  •  日久生厌
    2020-11-22 03:38

    You need to use exactly the ID as JSF has assigned in the generated HTML output. Rightclick the page in your webbrowser and choose View Source. That's exactly the HTML code which JS sees (you know, JS runs in webbrowser and intercepts on HTML DOM tree).

    Given a

    
        
    

    It'll look something like this:

    Where j_id0 is the generated ID of the generated HTML element.

    You'd rather give all JSF NamingContainer components a fixed id so that JSF don't autogenerate them. The is one of them.

    
        
    

    This way the form won't get an autogenerated ID like j_id0 and the input field will get a fixed ID of formId:emailAddress. You can then just reference it as such in JS.

    var input = document.getElementById('formId:emailAddress');
    

    From that point on you can continue using JS code as usual. E.g. getting value via input.value.

    See also:

    • How to select JSF components using jQuery?

    Update as per your update: you misunderstood the blog article. The special #{component} reference refers to the current component where the EL expression is been evaluated and this works only inside any of the attributes of the component itself. Whatever you want can also be achieved as follows:

    var input = document.getElementById('#{emailAddress.clientId}');
    

    with (note the binding to the view, you should absolutely not bind it to a bean)

    
    

    but that's plain ugly. Better use the following approach wherein you pass the generated HTML DOM element as JavaScript this reference to the function

    
    

    with

    function show(input) {
        alert(input.value);
    }
    

    If you're using jQuery, you can even go a step further by abstracting them using a style class as marker interface

    
    

    with

    $(document).on("click", ".someMarkerClass", function() {
        var $input = $(this);
        alert($input.val());
    });
    

提交回复
热议问题