JSF: SelectOneRadio shortcuts for options - javascript

I have the following h:selectOneRadio:
<h:selectOneRadio id="#{prefix}_rating" value="#{examinationPanel.tempResult}" >
<f:selectItems value="#{examinationPanel.options}"></f:selectItems>
</h:selectOneRadio>
And then the backing bean is loading the options based on some userpreferences:
public List<SelectItem> loadOptions (Set<ResultEnum> possibleResults){
List<SelectItem> options = new ArrayList<SelectItem>();
for(ResultEnum result:possibleResults){
SelectItem option = new SelectItem(result,messages.getString(result.name()));
options.add(option);
}
return options;
}
How can I define shortcuts for the options in the radio group? por example typing "1" selects the first option, typing "2" the second, etc...
Thanks in advance!
ps. I'm using Jsf 1.2, Richfaces, Primefaces and Facelets.

That's not by default builtin. Your best resort is using JavaScript. Attach a function to the keypress event of the <body>, check the keyCode of the key pressed and change the selected item of the dropdown accordingly. This is doable in only a few lines using jQuery. Here's an SSCCE, just copy'n'paste'n'run it.
<!doctype html>
<html lang="en">
<head>
<title>SO question 2461588</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$('body').keypress(function(e) {
var index = parseInt(String.fromCharCode(e.keyCode));
if (0 < index && index < 10) {
$('#dropdown option').eq(index - 1).attr('selected', true);
}
});
});
</script>
</head>
<body>
<select id="dropdown">
<option>option1</option>
<option>option2</option>
<option>option3</option>
<option>option4</option>
<option>option5</option>
<option>option6</option>
<option>option7</option>
<option>option8</option>
<option>option9</option>
</select>
</body>
</html>
If you want to support 10 or more items, you'll need to maintain a stack of pressed keys, apply it immediately and introduce a timeout to reset the stack (1 second?).

You can investigate whether <rich:hotKey> would help. In short, it lets you define keyboard shortcuts, but it may require some jQuery knowledge.

PrimeFaces hotKey can help as well.

Related

One-( keypress-)event-delay between javascript input and output

The following snippet reproduces the input text in the webpage using simple javaScript and jQuery.
I am wondering, though, how come there is a one character (or more precisely : one keystroke) latency between the input and the output
eg :
I type 'abcde'
the output is 'abcd'
however if I press the Insert key, the ultimate 'e' prints.
My code :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<input type="text" name="enteredText" id="myTextInput" />
<p id="myTextOutput">
blabla
</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$("#myTextInput").keypress(function( ){
var theText = $("#myTextInput").val();
$("#myTextOutput").html(theText);
});
$( "html" ).click(function( event ) {
var value = $("#myTextInput").val();
$("#myTextOutput").html(value);
});
</script>
</body>
</html>
Any idea ? Thanks
If you want to get rid of tat latency. use keyup or keydown instead of keypress:
$("#myTextInput").keyup(function( ){
var value = $("#myTextInput").val();
$("#myTextOutput").html(value);
});
Here is the DEMO
The most likely reason is that the keypress event handler is executed before the content of the input field is updated. When you read the content, you still read the old content, not the updated one.
From jQuery's keypress docs:
Note: as the keypress event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.
Using keyup instead fixes the issue:
$("#myTextInput").keyup(function() {
var theText = $("#myTextInput").val();
$("#myTextOutput").html(theText);
});
$("html").click(function(event) {
var value = $("#myTextInput").val();
$("#myTextOutput").html(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="enteredText" id="myTextInput" />
<p id="myTextOutput">
blabla
</p>
You're grabbing the value before you've allowed the event to propagate up to where the text field has been updated. You can add an infinitesimal delay to get the full value:
$("#myTextInput").keypress(function( ){
setTimeout(function() {
var value = $("#myTextInput").val();
$("#myTextOutput").html(value);
}, 0);
});

Check input elements responsively when changed

I have this code. It obviously calls function when selected element is focused. The function then checks if selected element has length less than 3, and if it does it changes background color of the element.
$('#register-form input[type="text"]').focus(function(){
if ($(this).length < 3) {
$(this).css('background','#f00');
}
});
Now the problem is that when there are more than 4 characters within input, color still remains. The problem is that it calls function when element is focused. After that, it doesn't check the if statement anymore, as obviosuly function is never called again.
The solution I seek; I want it to check if the IF statement is still legit once the input element value is changed. Or any other smooth way to check IF statements and calls functions in a live time.
The answer to this question is simple and well known. However, as you answer please provide some information related to this question; What are the best ways to check various changes in statements lively? What are the best ways to make website 'alive' and respond to any actions immediately?
Give the error a class and use onkeyup (and change if you wish - which triggers on blur too)
Also test the .val().length instead:
<style>
.error { background-color:red }
</style>
$('#register-form input[type="text"]').on("keyup,change",function(){
$(this).toggleClass("error", $(this).val().length < 3);
}).keyup(); // trigger on load
$(function() {
$('#register_form input[type="text"]').on("keyup", function() {
$(this).toggleClass("error", $(this).val().length < 3);
console.log("error")
}).keyup(); // initialise in case of reload
});
.error {
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="register_form">
<input type="text" />
<input type="text" />
<input type="text" />
</form>
Try this:
$('#register-form input[type="text"]').on("focus input", function(){
$(this).css('background', $(this).val().length < 3 ? '#f00' : '#fff');
});
EDIT
Personally, I use AngularJS alot for web applications that have alot of these. E.g. you can do this:
<input type="text" ng-model="myValue" ng-style="{'background-color', myValue.length < 3 ? '#f00' : '#fff'}"/>

Modal dialog box does not communicate with main HTA window

I have a javascript in an HTA which looks like this:
var result = null;
window.showModalDialog("dialog.hta", window, "dialogHeight:300px; dialogWidth:300px");
alert(result);
dialog.hta:
<html>
<head>
<title>Dialog box</title>
<meta http-equiv="MSThemeCompatible" content="yes"/>
</head>
<body style="background:#F0F0F0">
<select id="colors">
<option selected>Red</option>
<option>Blue</option>
<option>Green</option>
<option>Yellow</option>
</select><br/>
<script type="text/javascript">
function ok(){
window.dialogArguments.result = colors.getElementsByTagName("option")[colors.selectedIndex].innerHTML;
window.close();
}
</script>
<button onclick="ok()">OK</button>
<button onclick="window.close()">Cancel</button>
</body>
</html>
The problem is that when I press OK the alert(result) in the main HTA window always says null, even when I click on the OK button in the modal dialog box.
How can I do so that it says which option the user selects in the list when the OK button is pressed and null when the cancel button is pressed?
This is how modal dialog works:
In the main app:
// Call a dialog, and store the returned value to a variable
var result = showModalDialog(path, argument, options);
On dialog close:
// Set the returnValue
var elem = document.getElementById("colors");
window.returnValue = elem[elem.selectedIndex].text;
top.close();
After setting the returnValue in the dialog, you can read it from result after the dialog has been closed.
option elements didn't have innerHTML in old IEs, hence you've to use text property instead. You can also add a value attribute to the select element, and then create a return value in a simple way:
window.returnValue = document.getElementById('colors').value;

Drop down list width fit selected item text

Is there a way in javascript/jquery or css to make html <select>/#Html.DropDownList auto width so it fits currently selected item, I tried with diplay:inline-block and width:auto but width always seems to fit largest item on list?
My answer is similar to D3mon-1stVFW's, but instead uses a hidden drop-down to set the width on dynamically. As long as you use the same styling for your hidden and "real" one, it should account for different font sizes, decoration, etc. Here's the HTML:
<!-- this is our hidden "template" drop-down that we'll
use to determine the size of our "real" one -->
<select id="template" style="display:none;">
<option id="templateOption"></option>
</select>
<!-- this is our "real" template that will be re-sized -->
<select id="sel">
<option>Short</option>
<option>Really, Really, Really Long</option>
</select>​
And the Javascript:
function setSelectWidth() {
var sel = $('#sel');
$('#templateOption').text( sel.val() );
// for some reason, a small fudge factor is needed
// so that the text doesn't become clipped
sel.width( $('#template').width() * 1.03 );
}
$(document).ready( function() {
setSelectWidth();
$('#sel').change( function() {
setSelectWidth();
} );​
});
JSFiddle here: http://jsfiddle.net/kn9DF/1/
Variation on #Ethan Brown's answer, with the .val() corrected to .text() and a dynamically-created select so your page isn't polluted:
HTML:
<select id="sel">
<option>Short</option>
<option>Really, Really, Really Long</option>
</select>​
JS:
function setSelectWidth(selector) {
var sel = $(selector);
var tempSel = $("<select style='display:none'>")
.append($("<option>").text(sel.find("option:selected").text()));
tempSel.appendTo($("body"));
sel.width(tempSel.width());
tempSel.remove();
}
$(function() {
setSelectWidth("#sel");
$("#sel").on("change", function() {
setSelectWidth($(this));
});
});
Fiddle:
http://jsfiddle.net/kn9DF/242/
Tested on Chrome 39, FF 36, IE 11.
Here's a generic jQuery function you can drop into any page. It immediately resizes all selectors and ensures they will be resized when they are changed.
function setSelectWidth() {
var $yardstick = $('<select><option>' + $(this).val() + '</option></select>')
$yardstick.css({display: 'none'}).appendTo('body');
var fudge = 1.03; // need a little more to avoid clipping for some reason
$(this).width( fudge * $yardstick.width() );
$yardstick.remove();
}
function initSelectors() {
$('select').each(function() {
setSelectWidth.apply(this);
}).one('change', function() {
setSelectWidth.apply(this);
});
}
initSelectors();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- examples -->
<select id="example-1">
<option>Short</option>
<option>Really, Really, Really Long</option>
</select>
<select id="example-2">
<option>Tiny</option>
<option>A bit bigger</option>
<option>Huuuuuuuuuuuuuuuuuuuuge</option>
</select>
The script is forked from Ethan and Ian's answers. The initSelectors function does need to be re-called if you add a selector, but it uses jQuery one so it can be safely called multiple times if previous selectors remain on the page.
Use this sample I wrote. Use the same when you create the list, just get the default selected and set it in the span and get its width.
<script>
function newSelected(ele){
document.getElementById('jsize').innerHTML = ele.value;
document.getElementById('selectList').style.width = ($(jsize).width()+30)+'px';
}
</script>
<span id="jsize" style="display:none"></span><br />
<select id="selectList" onchange="newSelected(this);">
<option>small item</option>
<option>a really big long item</option>
</select>
​
see http://jsfiddle.net/39ffp/2/ it can be tweaked

Changing selection in a select with the Chosen plugin

I'm trying to change the currently selected option in a select with the Chosen plugin.
The documentation covers updating the list, and triggering an event when an option is selected, but nothing (that I can see) on externally changing the currently selected value.
I have made a jsFiddle to demonstrate the code and my attempted ways of changing the selection:
$('button').click(function() {
$('select').val(2);
$('select').chosen().val(2);
$('select').chosen().select(2);
});
From the "Updating Chosen Dynamically" section in the docs: You need to trigger the 'chosen:updated' event on the field
$(document).ready(function() {
$('select').chosen();
$('button').click(function() {
$('select').val(2);
$('select').trigger("chosen:updated");
});
});
NOTE: versions prior to 1.0 used the following:
$('select').trigger("liszt:updated");
My answer is late, but i want to add some information that is missed in all above answers.
1) If you want to select single value in chosen select.
$('#select-id').val("22").trigger('chosen:updated');
2) If you are using multiple chosen select, then may you need to set multiple values at single time.
$('#documents').val(["22", "25", "27"]).trigger('chosen:updated');
Information gathered from following links:
1) Chosen Docs
2) Chosen Github Discussion
Sometimes you have to remove the current options in order to manipulate the selected options.
Here is an example how to set options:
<select id="mySelectId" class="chosen-select" multiple="multiple">
<option value=""></option>
<option value="Argentina">Argentina</option>
<option value="Germany">Germany</option>
<option value="Greece">Greece</option>
<option value="Japan">Japan</option>
<option value="Thailand">Thailand</option>
</select>
<script>
activateChosen($('body'));
selectChosenOptions($('#mySelectId'), ['Argentina', 'Germany']);
function activateChosen($container, param) {
param = param || {};
$container.find('.chosen-select:visible').chosen(param);
$container.find('.chosen-select').trigger("chosen:updated");
}
function selectChosenOptions($select, values) {
$select.val(null); //delete current options
$select.val(values); //add new options
$select.trigger('chosen:updated');
}
</script>
JSFiddle (including howto append options):
https://jsfiddle.net/59x3m6op/1/
In case of multiple type of select and/or if you want to remove already selected items one by one, directly within a dropdown list items, you can use something like:
jQuery("body").on("click", ".result-selected", function() {
var locID = jQuery(this).attr('class').split('__').pop();
// I have a class name: class="result-selected locvalue__209"
var arrayCurrent = jQuery('#searchlocation').val();
var index = arrayCurrent.indexOf(locID);
if (index > -1) {
arrayCurrent.splice(index, 1);
}
jQuery('#searchlocation').val(arrayCurrent).trigger('chosen:updated');
});

Categories

Resources