How to pass JavaScript values to JSF EL and backing bean?
Asked Answered
L

1

7

I am doing JSF geolocation service where I need to pass latitude and longitude to bean for processing. HTML5 allows getting location with JavaScript, for example like is done in http://code.google.com/p/geo-location-javascript/. Putting following code to JSF page shows alert with GPS coordinates

<script>
    if (geo_position_js.init()) {
        geo_position_js.getCurrentPosition(success_callback,error_callback,{enableHighAccuracy:true,options:5000});
    } else {
        alert("Functionality not available");
    }
    function success_callback(p) {
        alert('lat='+p.coords.latitude.toFixed(2)+';lon='+p.coords.longitude.toFixed(2));
    }

    function error_callback(p) {
        alert('error='+p.message);
    }
</script>

How to use p.coords.latitude.toFixed(2) value to pass it for example to h:inputtext component?

Lamarre answered 14/1, 2011 at 22:37 Comment(0)
C
13

You need to realize that JSF runs at webserver and produces a bunch of HTML/CSS/JS code which get sent from webserver to webbrowser and that the webbrowser only runs HTML/CSS/JS. Rightclick the page in webbrowser and choose View Source. In place of the <h:inputText> you'll see something like

<input type="text" id="formid:inputid" />

In JS, you can easily grab HTML elements from the HTML DOM using document functions and alter it.

var input = document.getElementById('formid:inputid');
input.value = 'new value';

See also:

Chloris answered 14/1, 2011 at 22:52 Comment(2)
does this work in facelets ? because i used it but it keeps returning a null value at the backing beanBechtold
@Developer106: JSF/Facelets just runs on webserver and generates HTML. JS is part of HTML and runs on webbrowser. It's totally irrelevant to JS how that HTML is generated. If you "keep getting null" then it can only mean that you don't understand how JSF/Facelets and HTML/JS works.Chloris

© 2022 - 2024 — McMap. All rights reserved.