Hatena::ブログ(Diary)

masdoiの日記 RSSフィード

2008-01-06

1つのformで複数ボタンの配置

| 12:48 | 1つのformで複数ボタンの配置を含むブックマーク

1つのformで複数ボタンを作り、どのボタンが押されたのかをCGI側で判定したい場合があります。

まずこのようなJavaScriptを定義しておきます。

			<script>
                                function do_submit(target) {
                                  window.document.form1.target.value = target ;
                                  document.form1.submit();
                                }
                         </script>

formのHTMLはこのようになります。


  <form action="/some_cgi" method="post" name="form1">

    <input type=hidden name="target" value="">

    <input type="button" name="button" value="ボタン1" onclick="do_submit('button1')">
    <br>
    <input type="button" name="button" value="ボタン2" onclick="do_submit('button2')">


hiddenタグにどのボタンが押されたかの識別の文字列をセットする方法です。この場合は'button1' or 'button2'。

リクエストを受けるCGI側ではこのhiddenのtarget属性の値を見て判定出来ますね。

ボタンのラベル名に日本語を使用したい場合などはこのやり方がいいと思います。

(追記 2008/06/24)

sbumitボタンの代わりに画像を外観に使いたい時など有効ですね(^^)