Search code examples
substringzk

How to get substring in zk?


There is this example:

<grid width="100%">
    <rows>
        <row>onChanging textbox: <textbox id="t1" onChanging="copy.value = event.value"/></row>
        <row>Instant copy: <textbox id="copy" readonly="true"/></row>
    </rows>
</grid>

Can I somehow copy just a substring of event.value, say the first 4 characters? I tried things like onChanging="copy.value = $(substring(event.value, 0, 4)), but the syntax is incorrect.

Thanks for the help and thumbs down appreciated.


Solution

  • That's a simple task, you just need to do something like this:

    <grid width="100%">
        <rows>
            <row>onChanging textbox: <textbox id="t1" onChange='copy.setValue(self.getValue().substring(0,3))' instant="true"/></row>
            <row>instant copy: <textbox id="copy" readonly="true"/></row>
        </rows>
    </grid>
    

    However, you have to be careful because if you try to do a substring when the value in the first textbox is smaller that the lenght of the substring you are trying to get, then you will get an error:

    String a1 = "ho";
    String a2 = a1.substring(0,3) //Here you will have an error...
    

    So I will recommend you to make a validation before and then do the substring... like this:

    <grid width="100%">
        <rows>
            <row>onChanging textbox: <textbox id="t1" onChange='copy.setValue(self.getValue().length() >= 3? self.getValue().substring(0,3):"")' instant="true"/></row>
            <row>instant copy: <textbox id="copy" readonly="true"/></row>
        </rows>
    </grid>
    

    Check that in the validation self.getValue().length() >= 3 the number 3 is the same number of letters I want to get in the substring self.getValue().substring(0,3)

    I made an example for you: http://zkfiddle.org/sample/3afnseb/2-onChange-copy-textbox-example