JSF: SelectOneRadio shortcuts for options
-
20-09-2019 - |
Question
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.
Solution
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?).
OTHER TIPS
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.