Quantcast
Channel: XPages – Xcellerant
Viewing all articles
Browse latest Browse all 216

Dojo in XPages – 6: Selecting a DOM Element with dojo.byId()

$
0
0

dojo.byId() is a simple function to get a handle to a DOM element on your page, based on it’s ID. Once you have that handle, you can manipulate it as needed. In this post, we’ll take a look at why and how to use it.

Why use it?

dojo.byId() is basically the same thing as document.getElementById(). So why is it worth using?

1. It’s shorter, so it’s convenient.
2. Older browser support. IE 7 and earlier will also return an element whose name attribute matches the value, which may not be the behavior you’re looking for.

Getting an HTML Field

Use of dojo.byId is very straightforward when obtaining a handle to a pure HTML element.

For example, if you have this field on your page:

<input id="htmlField" />

You can obtain a handle to it as follows:

var myField = dojo.byId('htmlField');

If you want to set the value of the field, you can get a handle to it, then set its value property.

dojo.byId('htmlField').value = 'new value 1';

One of the great things about working with client-side JavaScript is that you can also easily test this in the console of the browser tools without having to write it in Domino Designer, save, build, refresh, then test. Streamline your development by testing client-side code in the browser directly!

Dojo 6b

Getting an xp:inputText Field

As you are undoubtedly aware, client-side DOM element IDs of XPages components aren’t quite so simple. For example, on this simple page where I only have one xp component named xpField, the generated client-side id is view:_id1:xpField.

Fortunately, expression language (EL) syntax is available to compute that ID for you: "#{id:ComponentName}"

This code will get a handle to the field:

var myField = dojo.byId('#{id:xpField}');

When you include EL within client-side code, it is evaluated on the server and replaced with the actual string before being rendered on the page. (This works within both xp buttons and pass-thru HTML buttons.)

When you put that code on button, this is what gets rendered on the page:

var myField = dojo.byId('view:_id1:xpField');

To set the value of the field, you can use this code:

dojo.byId('#{id:xpField}').value = 'new value 2';

You can’t test this quite as easily in the browser console, but if you inspect the design and get the XPages ID of the field, you can still do it.

Dojo 6c

Once you’ve determined the client-side ID, you can write the code in the console to test it out.

Dojo 6d

We’ll dig into more DOM element manipulation later in the series, but for now, get used to using this handy method. Just watch the casing — you may be tempted to use dojo.byID(), but that won’t work because the last ‘D’ is capitalized.



Viewing all articles
Browse latest Browse all 216

Trending Articles