I need to dynamically add values from a text input to a listbox field. Basically, I am making a custom multi-line text component. The following works with a standard <h:selectOneListbox>, but when I use the PrimeFaces equivalent, <p:selectOneListbox>, nothing seems to happen. I am using all PrimeFaces inputs in my application, and I want to keep the look consistent.
<!--This works:-->
<h:form id="mainForm">
<p:inputText id="txtInput" /><p:commandButton value="Add" id="addTxt"
onclick="addText()"/>
<h:selectOneListbox id="selectTxt"/>
<script type="text/javascript">
function addText(){
var txtInput = $('#mainForm\\:txtInput').val();
var opts = $('#mainForm\\:selectTxt').prop('options');
opts[opts.length] = new Option(txtInput,txtInput,true,true);
}
</script>
</h:form>
<!--This doesn't work:-->
<h:form id="mainForm">
<p:inputText id="txtInput" /><p:commandButton value="Add" id="addTxt"
onclick="addText()"/>
<p:selectOneListbox id="selectTxt"/>
<script type="text/javascript">
function addText(){
var txtInput = $('#mainForm\\:txtInput').val();
var opts = $('#mainForm\\:selectTxt_input').prop('options');
opts[opts.length] = new Option(txtInput,txtInput,true,true);
}
</script>
</h:form>
Thanks in advance for the help.
The
<p:selectOneListbox>uses an<ul><li>instead of<select><option>to present the options (with the simple reason that there’s then so much more freedom to give it a different look’n’feel). That’s exactly the reason why you can’t just create and add newOptionelements. Rightclick page in browser and do View Source and you’ll understand it much better (if you’re already familiar with basic HTML, of course).Please note that adding new options this way will indeed seem to work for
<h:selectOneListbox>, but that this is purely visually, in the client side. JSF won’t accept the in the client side created items on submit, but throw aValidation Error: Value not validwith the simple reason that the submitted value is not part of the items as available in the server-side definied<f:selectItems>.You need to use JSF instead of JavaScript to manipulate the
<f:selectItems>value. This way it will work in<p:selectOneListbox>as well.Here’s a concrete kickoff example how to do it using pure JSF:
With:
That’s all.
See also: