LoginSignup
0
0

More than 3 years have passed since last update.

h:commandButtonで確認ダイアログでOKの時だけaction属性の処理を実行する方法

Last updated at Posted at 2020-08-08
  • 環境
    • CentOS Linux release 7.8.2003 (Core)
    • Eclipse IDE for Enterprise Java Developers.Version: 2020-03 (4.15.0)
    • openjdk version "11.0.7" 2020-04-14 LTS
    • JSF 2.3.9

やりたいこと

  1. ボタンを押下すると確認ダイアログを表示する
  2. 確認ダイアログで[OK]ボタンを押下するとaction属性のビジネスロジックを実行する
  3. 確認ダイアログで[キャンセル]ボタンを押下するとなにもしない

確認ダイアログでOKの時だけaction属性の処理を実行する方法

※. htmlタグ、next.xhtmlは省略
確認ダイアログは、window.confirmを利用

base.xhtml
<h:head>
  <title>ponsukeのQiita用</title>
  <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
  <h:outputScript library="js" name="base.js"/>
</h:head>
<h:body>
<h3>ここはA画面</h3>
<h:form id="formId">
  <div>
    <h:commandButton value="画面遷移"
      onclick="return confirmMessage();"
      action="#{sampleBean.showNextPage()}" />
  </div>
</h:form>
</h:body>
base.js
/**
 * 確認ダイアログを表示する.
 * @return {boolean} 確認ダイアログでの選択結果 true:OKボタン押下.
 */
function confirmMessage() {
    return window.confirm('画面遷移していい?');
}
SampleBean.java
package brans;

import javax.faces.view.ViewScoped;
import javax.inject.Named;

@Named
@ViewScoped
public class SampleBean implements Serializable {
    /** serialVersionUID. */
    private static final long serialVersionUID = -6782548672735889274L;
    /**
     * 次のページを表示する.
     * @return 次のページ.
     */
    public String showNextPage() {
        return "next.xhtml";
    }
}

失敗事例 : onclick属性でreturnしない

base.jsでreturnしているんだから、もうよくね?と思ってしょっちゅう失敗する。
確認ダイアログの結果にかかわらずaction属性の処理が実行される。
理由をだれか説明してほしい・・・。

base.xhtml
<!--省略-->
    <h:commandButton value="画面遷移"
      onclick="confirmMessage();"
      action="#{sampleBean.showNextPage()}" />
<!--省略-->
こうやって書くのはボタンごとにちゃんと動作する
    <h:commandButton value="画面遷移"
      onclick="return window.confirm('画面遷移していい?');"
      action="#{sampleBean.showNextPage()}" />
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0