simon peter
simon peter

Reputation: 403

XPages:How to get element value CSJS

Using the Bootstrap Application layout, i have been trying to get the value of an element but unable to do so, i have try several code like

XSP.getElementById("#{id:elementName}").value
$("#{id:elementName}").val()
x$("#{id:elementName}").val()
dojo.byId("#{id:elementName}").value

but non of the four is working, how do i get the value of element from clientside

Upvotes: 0

Views: 2913

Answers (1)

Cameron Gregor
Cameron Gregor

Reputation: 1460

2 Things to check.

  1. Is the XSP.getElementById("#{id:elementName}") code correctly finding the element? Note: you should be using the server side control Id here and not any other property e.g. name won't work. if you are trying to do it by name then you should use another method.

  2. What type of element are you trying to get? if it is a text input then you can use .value but if it is a select, or some other type of control it might be a different method/property

To check you are correctly finding the element try this (in a CSJS button event):

var el = XSP.getElementById('#{id:serverSideControlId}');
console.log(el);

Click the button then check your javascript console in your browser, you should see some sort of info on your console representing your element e.g.:

<input type="text" name="view:_id1:inputText1" id="view:_id1:inputText1">

If it can't find the element then your id's must be wrong and you will see null

Once you are sure you are getting the element, then you can try using the XSP.getFieldValue(node) function which I think has some smarts within it to correctly find the value depending on the type of element.

// Note that you pass in the element that you retrieved already, and not the id
var val = XSP.getFieldValue(el);

Here is a working example with a InputText:

<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">

    <xp:inputText id="inputText1" value=""></xp:inputText>

    <xp:button value="Get Element Value" id="button1">
        <xp:eventHandler event="onclick" submit="false">
            <xp:this.script><![CDATA[

        var el = XSP.getElementById('#{id:inputText1}');

        // Check your javascript console in your browser
        console.log(el);

        var val = XSP.getFieldValue(el);

        // Check the contents of the value 
        console.log(val);

        ]]></xp:this.script>
        </xp:eventHandler>
    </xp:button>


</xp:view>

Upvotes: 2

Related Questions