【发布时间】:2017-05-05 02:46:06
【问题描述】:
我有一个 JSF 页面(已经在标题中注册了 jQuery)包含 indicator、reason 和一个用于提交 h:form 的 h:commandButton。 indicator 有两个值 Y 和 N。
我尝试构建的逻辑是当页面加载和indicator = Y(在下面的 jQuery 中是indicator.data("prev") == 'Y'),如果用户从Y 切换到N 但不在reason 中输入任何单词,甚至用户点击h:commandButton,表单应该不提交。
简而言之,在提交之前,应该检查指标当前值和之前值关系的状态是从Y变为N(我在jQuery脚本部分设置了这个逻辑部分),还需要检查原因不为空. 我猜想实现这样的检查操作可能需要重新组织代码结构。
下面是我当前的代码,它缺少这个逻辑,从不禁止提交并导致支持 bean 的冲突,.由于我是 jQuery 和 JSF 的新手,有人可以告诉我如何防止这种提交吗?谢谢。
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"
xmlns:fn="http://java.sun.com/jsp/jstl/functions"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich">
<h:head>
<title>myPage</title>
<h:outputScript name="jquery.js" target="head"/>
</h:head>
<f:event type="preRenderView" listener="#{myPage.getmyPage}" />
<h:body>
<f:view>
<h:form name ="myPage" id ="myPage">
<table>
<tr>
<td align="left">
<h:selectOneMenu id="indicator" value="#{myPage.indicator}">
<f:selectItem itemValue="Y" itemLabel="YES" />
<f:selectItem itemValue="N" itemLabel="NO" />
</h:selectOneMenu>
</td>
<td>
<h:inputTextarea id="reason" value="#{myPage.reason}">
</h:inputTextarea>
</td>
<td>
<h:commandButton id="submit" value="Submit"
onclick="if (! confirm('Do you want to update?')) return false" action="#{myPage.update}">
</h:commandButton>
</td>
</tr>
</table>
</h:form>
</f:view>
// TODO: I want to add the logic to prevent h:commandButton submit(e.g disable the button) when reason is empty
// and indicator value turn from 'Y' to 'N', the jQuery section reflect the case when toggle from 'Y' to 'N',
// reason editable, as it need to consider two elements(indicator value/ reason value) at the same time,
// how should the code look like ?
<script type="text/javascript">
$(window).load(function() {
var indicator = $(document.getElementById("myPage:indicator"));
// set the indicator pre data
indicator.data("prev", indicator.val());
// Handle initial status of indicator, when page load, if it is 'Y' open reason field
// if it is 'N' disable reason field,
if(indicator.data("prev") == 'Y') {
$(document.getElementById("myPage:reason")).prop('disabled', false);
} else {
$(document.getElementById("myPage:reason")).prop('disabled', true);
}
// Handle change status of indicator,
indicator.change(function(data){
var jqThis = $(this);
var after_change = jqThis.val();
var before_change = jqThis.data("prev");
if(before_change == 'Y' && after_change == 'N'){
$(document.getElementById("myPage:reason")).prop('disabled', false);
}
});
});
</script>});
</h:body>
【问题讨论】:
标签: javascript jquery html jsf