JSF: Prefilled values with input text field? - java

I tried searching, but haven't found the answer. I see when you ask a question on stackoverflow, the input field for "tags" show the gray text "at least one tag such as...etc". Upon click, the gray text disappears and you can start typing your values. If I click off that, the instructions reappear. How do I do that? Are there out of box implementations of this functionality or does this require custom implementation?
Thanks!

Two JSF component libraries offering this functionality comes to mind:
OpenFaces input text with Prompt text
PrimeFaces Watermark

It's a blur/focus javascript event handler on the input field. In jQuery it would be something like the following:
HTML
<input type="text" name="your-input" id="your-input" title="Enter a value"/>
jQuery
$('#your-input').focus(function(){
var defaultVal = $(this).attr('title');
if($(this).val() == defaultVal)
$(this).val('');
});
$('#your-input').blur(function(){
var defaultVal = $(this).attr('title');
if($(this).val() == '')
$(this).val(defaultVal);
});
$('#your-input').trigger('blur');
It takes the default value from the input's title attribute and sets its value on focus and blur events depending on the current value of the input. The last trigger() call is so the input's value is correctly set when the page loads.
You can see it in action here.

The simplest example would be
window.onload = function() {
var txtField = document.getElementById('textField');
if(!txtField.value) {
txtField.value = 'Default Text';
}
}
<h:inputText id="txtField" value="#{bean.txtField}"
onfocus="window.default=this.value; this.value='';"
onblur="if(!this.value) { this.value = window.default; }"/>
In any case I would suggest to switch the window.onload to any dom ready function such as
document.observe('dom:loaded', function(){}); // Prototype
$(document).ready(function(){}); // jQuery

Related

pass java object to bootstrap modal

i'm trying to pass a java object to be displayed in my bootstrap modal...In each row of my datatable i have this code :
<td><a href="#" class="btn btn-warning edit" data-toggle="modal" data-whatever="${u}" data-target="#exampleModal">
Where ${u} is my object to be displayed....
I tried this jquery code :
<script type="text/javascript">
$('#exampleModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget); // Button that triggered the modal
var recipient = button.data('whatever'); // Extract info from data-* attributes
var modal = $(this);
modal.find('.modal-title').text('New message to ' + recipient);
modal.find('.modal-body input').val(recipient);
});
It's showing something like in this picture modal picture
I don't know if there is a way do display each property of the object in each field...i googled a lot without success...Does anyone have an idea ??Thanks
It looks like you are assigning an object to the data.whatever="${u}", but since objects don't exist in HTML the way they do in Java for example, your object is being turned into a String when the page is sent to the client.
I'm guessing what you intend to do is to have each one of the inputs have a different field on the same object. If that is the case, then you would want to have data.whatever = "${u.fieldName}" and you can have a different fieldName for each one of your inputs in your modal.

Java Spring MVC form:checkboxes - how to know if any were checked

Say I have the following line in my JSP:
<form:checkboxes path="appliedPlayers" items="${suitablePlayers}" itemValue="id" itemLabel="displayName" />
I would like to disable the form-submit button when none of the checkboxes are checked. Something like:
$('#checkboxes').change(function() {
if (none_are_checked)
disableBtn();
});
Spring form tags does not support this. You can check the following link for supported attributes.
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/spring-form-tld.html#spring-form.tld.checkboxes
What can be done is, you can handle this scenario at the client side using jQuery(like you mentioned).
<script>
$(document).ready(function(){
$('input[name=players]').change(function() {
//alert('hello');
var checkedNum = $('input[name="players[]"]:checked').length;
if (!checkedNum) {
// User didn't check any checkboxes
disableBtn();
}
});
});
</script>
Explanation: in the above code snippet, when checkbox element changes then the registered function gets called which counts the number of selected checkbox elements. If zero then it enters if condition which is the requirement.
Note: above example assumes html attribute name value for checkboxes are players. You can change your jquery selectors appropriately if needed.
Credit:
https://stackoverflow.com/a/16161874/5039001

access javascript variable value in jsp

I want to pass a javascript variable to my servlet, where I need to use it.
In javascript, the variable count returns the rows of my table and I can show count in the jsp, using $('#counter').html(count); , but I cannot pass count's value to my servlet. I tried document.getElementById("hiddenField").value=count; but it doesn't work.
Javascript
<script>
var count = 3;
$(function() {
$('#counter').html(count);
$('#addButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
});
$('#deleteButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
});
});
document.getElementById("hiddenField").value=count; // ???
</script>
JSP
Count: <span id="counter"></span> <%-- it works --%>
<form method="post" action="newteamsubmit">
...
<input type="hidden" id="hiddenField" name ="countRows" />
<input type="submit" name ="button1" value=" Submit " />
<input type="submit" name = "button1" value=" Cancel " />
</form>
Servlet
String cr = request.getParameter("countRows"); //I' ve tried also to convert it
// to int, but that's not my problem, since I cannot pass the value as a start
I've spent many hours, trying to figure out how I can access a javascript variable in jsp, but I haven't found any solution.
Thanks in advance.
The count is computed each time the add button or the delete button are clicked. But you only set the hidden field value once, when the page is loaded (and its value is thus hard-coded to 3).
You must set it, as you're doing for the #counter element, in your click handlers:
$('#addButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
$('#hiddenField').val(count);
});
$('#deleteButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
$('#hiddenField').val(count);
});
Also note that you're repeating exactly the same code in two click handlers here. You should do that only once, for the two buttons:
$('#addButton, #deleteButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
$('#hiddenField').val(count);
});
or even, since you're using jQuery:
$('#addButton, #deleteButton').bind('click', function() {
count = $("#dataTable tr").length;
$('#counter').html(count);
$('#hiddenField').val(count);
});
document.getElementById('hiddenField').value is not set because it is outside your document.ready. Put it inside your click handler.
Make sure of 2 things -
There is only one element with id "hiddenField" on your page.
Make sure that the following code
document.getElementById("hiddenField").value=count;
is after in the page.
Just make sure that js sets the hiddenField after the element has been loaded.
3. check for any JS errors using Javascript console.
Rest it looks good
The main issue here is that you are trying to access from the server, a variable that only exists at the client. To access that variable you have to send it from the client to the server using AJAX to trigger some form of API in the backend. REST, SOAP or XML-RPC are common technologies used for this sort of thing. The server side code is used for generating the UI and providing it with data from a database or such. Commonly the UI is generated only once, and then the client calls the server asking for more data in response to user actions, like clicking a button.
Imagine a table filled with information about books: title, author, publish date etc. This table can get quite large, and traditionally this table will be split up over several pages and possibly a dynamic filter. To save bandwidth and increase the user experience by not loading the entire page from scratch you can use AJAX to ask the server for just the relevant data. Doing so the page updates dynamically and smoothly for the user.
In your case, you can use this technique to update the server every time the user clicks the button.
If however you are really just looking to update a hidden field in a form with a value as the user performs actions, and the server wont do anything with it except show it you can just use javascript.
Remember also that the request variable contains the data you post to the server when you submit the form. The servlet will get the data after the client has posted it, which is after the JSP has generated the page. The sequence of the code execution is JSP -> Javascript -> Servlet.
Hope this helps!
You can use this way:
document.forms[0].countRows.value = counter
Hope this will help you

Publish an event using Struts 2 jQuery Plugin

I want to use the publish/subscribe framework which is used internally by Strust2 jQuery plugin.
The user can select an account number from a list or type it in a textbox.
I want to publish an event when text box or select option changes. So the user can only type textbox OR select something from select box:
<s:textfield name="account" onblur="$.publish('accountChanged',this,event)"/>
<s:select name="accountList" list="destinationAccounts"
onblur="$.publish('accountChanged',this,event)"/>
Below is the js:
$.subscribe('accountChanged', function(event, data) {
alert("New data is: " + data.value);
if ( event.target.id=='account') {
//Do something
}
}
Here are issues:
The data.value only works for textbox, for select box the data.value is undefined.
I want to know which target received the event. event.target.id is not working! I think the event object is not a jQuery event object?
I reviewed the sample showcase application, but could not find any.
Am I calling $.publish method correctly? Are there better ways?
If you subscribe to topics keep the topic name unique for each tag that allows to separate handlers for the tag. The new event is created each time you publish the topic in the onblur event. The textfield handler for topic works as you described. The select tag doesn't work because wrong parameter passed as the data. The example of the working code
<s:textfield name="account" onblur="$(this).publish('accountChanged', this, event)"/>
<s:select name="accountList" list="{'list1', 'list2','list3'}" onblur="$(this).publish('accountListChanged', this, event)"/>
<script type="text/javascript">
$.subscribe('accountChanged', function(event, data) {
alert("accountChanged: " + data.value);
});
$.subscribe('accountListChanged', function(event, data) {
alert("accountListChanged: " + data.parentElement.value);
});
</script>
As you can see the data.value is undefined because data.parentElement.value should be used. event.target.id is not working because event.originalEvent.target.id should be used. The event object is a jQuery event, but originalEvent is DHTML object which is blur.
I don't know about your requirements, if you need to subscribe/publish events or use the original event handlers, I can't say what is better in this situation.
The below code solved my issue:
As I could not find any example of publish/subscribe framework, I hope below example will help others!
The jsp will be
You must call ${this).publish not $.publish
<s:textfield name="account" onblur="$(this).publish('destinationChanged', this, event)"/>
<s:select name="accountList" list="{'list1', 'list2','list3'}" onblur="$(this).publish('destinationChanged', this, event)" emptyOption="true"/>
<s:textfield name="destinationAccount" type="hidden" />
And the JS will be
$.subscribe('destinationChanged', function(event, data) {
//If user types in the textbox
//then get the value and make the select box shows an empty option
if( !!data.value){
destinationAccount= data.value;
$('#destinationKnownAccount').val($("#destinationKnownAccount option:first").val());
} else{
//The user selected an account from select box.
// So get the value from select box and clean textbox
destinationAccount= data.parentElement.value;
$('#destinationUnknownAccount').val('');
}
//Set the hidden box
$('#destinationAccount').val( destinationAccount);
});
As mentioned one can use event.originalEvent.target.id to find which target was selected.

Use Javascript to change text box back colour if wrong, before posting

I want to carry out some validation in javascript before posting, so basically I want to:
Alter textbox value
use Onchange attached to the textbox to fire off a Javascript script.
the script will check that a colon is at the right place in the value.
if that isnt the case, change the textbox back colour to red.
all this is done before secondary validation in the struts form and action.
first problem is I cannot seem to pass the textbox value to the script, is this prevented under struts?
second problem is the changing of the back colour of the textbox on error.
<html:text property="date1_1" maxlength="8" value="<%=WeekOne.get(1)%>" size="15" onchange="validateBox(this.value)"/>
<script type="text/javascript">
function validateBox(textBox)
{
alert("here");
var p = textBox.value();
alert(p);
}
</script>
To solve your problems you need to fix some errors in the code. I will show you what to fix trying to achieve what you've written by numbers.
To alter textbox value you need to pass the textbox element itself not the value.
You already use it
doing some checks in the script against textbox value (value is not a function)
for this you should use background color CSS property of the textbox
assume second validation is on the server, checks are done on the client via javascript
For example
<html:text property="floor" styleClass="input" size="30" tabindex="12" onchange="validateBox(this)"/>
<script type="text/javascript">
var textBoxBackgroundColor;
function validateBox(textBox) {
var p = textBox.value;
if (textBoxBackgroundColor == null)
textBoxBackgroundColor = textBox.style.backgroundColor;
//validate
if (p < 0)
textBox.style.backgroundColor = '#000000';
else
textBox.style.backgroundColor = textBoxBackgroundColor;
}
</script>
will check that textbox floor is positive.

Categories