问题
So far I've not been able to hit on the right way to do it. I've got an inputText bound to a variable in an object. I've got a selectOneMenu item dropdown all full of goodness. The thought was that when selected, I'd just push the selected text from the dropdown into the input box (simulating typing it). Apparently that's a no go. I can grab the text of the selected element in a javascript onselect handler easily enough, but the inputText refuses to accept it (presumably choosing to redisplay the stored empty string rather than accept this as input and push it to the object). I've also tried setting the string directly in Java, but with the exact same results (of nothing happening). Apparently my entire approach is flawed. What's the right way to do this? Some sample xhtml code that doesn't work follows (the java involved is simple getter/setter):
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<script type="text/javascript">
function dropdownSelect() {
var element=document.getElementById("form:dropdown");
var text=element.options[element.selectedIndex].value;
document.getElementById("form:part").textContent=text; // TODO doesn't work. Neither does forcing the part number to change inside the object via Java code
}
</script>
<h:body>
<h:form id="form">
<h:inputText id="part" value="#{part.partNumber}"/>
<h:selectOneMenu id="dropdown" onselect="dropdownSelect()">
<f:selectItems value="#{part.list}"/>
</h:selectOneMenu>
</h:form>
</h:body>
</html>
回答1:
There are two mistakes:
The
select
event is the wrong event to hook on change of the HTML<select>
element. You needchange
instead.<h:selectOneMenu id="dropdown" onchange="dropdownSelect()">
The
textContent
property doesn't exist on HTML DOM object representation of the HTML<input>
element, the HtmlInputElement. You needvalue
instead.document.getElementById("form:part").value = text;
Neither of those problems are related to JSF. It's just basic HTML/JS. You'd have exactly the same problem on the same HTML content generated by PHP, ASP or even plain HTML.
For the case you're interested, the "JSF-ish" way would be something like follows:
<h:form>
<h:inputText id="part" value="#{part.partNumber}"/>
<h:selectOneMenu value="#{part.selectedNumber}">
<f:selectItems value="#{part.list}"/>
<f:ajax listener="#{part.changeNumber}" render="part" />
</h:selectOneMenu>
</h:form>
with
public void changeNumber(AjaxBehaviorEvent event) {
partNumber = selectedNumber;
}
来源:https://stackoverflow.com/questions/14265811/how-to-populate-inputtext-from-selectonemenu-item