Search code examples
javascriptzk

How get the zk element id from js


I am working with ZK and I want to get the id of the a zk element from js. I have used differents ways:

Declaring the component like native html and it gets the id from js but it isn't correct. I have declared the element using the html tags of ZK but isn't correct too. I have seen some functions like Component.getFellow('component_name') and finally I have read about the UUID and use some example codes but I can't the element id for example:

<label id=titleBook/>

from javaScript.

any idea? Thank you.


Solution

  • The problem you're running into is that the id you assign an element in ZUL (ZK markup) is not one-to-one with the rendered DOM element id. ZK does this for a number of reasons, but the take away is that you need to reference the DOM elements without knowing their id.

    ZK makes this easy by giving you a JavaScript framework also, they refer to it as 'Client Side Programming' a lot.

    Have a look at ZK's documentation on Client Side Programming, specifically the paragraph on "How to Get Widget Reference in JavaScript".

    Here you'll see that the ZK JavaScript APIs provide

    <zk xmlns:w="http://www.zkoss.org/2005/zk/client">
        <label id="titleBook"/>
        <button label="button"
                w:onClick="this.$f('titleBook').setValue('sean is cool')" />
    </zk>
    

    Note that I am defining the w namespace to be ZK's client library just to fire the client side onClick event where I have access to this, the Button widget.

    It sounds like you are probably working in vanilla JS would do something more like..

    <zk>
        <script defer="true">
            jq("$titleBook").css('color', 'green');
            zk("$titleBook").setValue('sean is cool');
        </script>
        <label id="titleBook"/>
    </zk>
    

    Here we're leveraging the jq() and zk() globals in the ZK JavaScript APIs. The former is just jQuery's $() and the latter is the ZK counterpart. The difference is that the jQuery function returns a jQuery object while the latter returns a ZK widget. Both are extended to support the new $ CSS style selector which references the ZK widget id (what you assigned in ZUL/Java).