2012年8月23日木曜日

開発環境

『初めてのJavaScript 第2版』(シェリー・パワーズ著(Shelley Powers著)、武舎 広幸+武舎 るみ訳、オライリー・ジャパン、2009年、ISBN978-4-84311-425-5) の8章(フォームと検証)練習問第8-1解いてみる。

その他参考書籍

8-1.

コード(TextWrangler)

<script>
catchEvent(window,"load",setupEvents);
function catchEvent(o,e,h){
  if(o.addEventListener){
    o.addEventListener(e,h,false);
  } else if(o.attachEvent){
    e = "on" + e;
    o.attachEvent(e,h);
  }
}

function cancelEvent(e){
  if(e.preventDefault){
    e.preventDefault();
    e.stopPropagation();
  } else {
    e.returnValue = false;
    e.cancelBubble = true;
  }
}

function setupEvents(e){
  catchEvent(document.getElementById("someForm"),"submit",checkColors);
}

function checkColors(event){
  var theEvent = event ? event : window.event;
  var colorOpts = 
    document.getElementById("someForm").
    getElementsByTagName("input");
  
  var message = "どれかひとつ色を選んでください";
  for(var i=0; i<colorOpts.length; i++){
    if(colorOpts[i].checked){
      var n = Math.random();
      message = n > 0.75 ? "大吉" :
                n > 0.5 ? "小吉" :
                n > 0.25 ? "中吉" :
                "凶";
      message = "今日のあなたの運勢は" + message + "です";
      break;
    }
  }
  $('#d0').text(message);
  cancelEvent(theEvent);
}
</script>
<p>今日のカラー占い</p>
<p>お好みの色をお選びください。</p>
<form id="someForm" action="">
<p>
<input type="radio" value="赤" name="radiogroup" />赤
<input type="radio" value="青" name="radiogroup" />青
<input type="radio" value="黄色" name="radiogroup" />黄色
<input type="radio" value="白" name="radiogroup" />白<br />
<input type="submit" value="送信" />
</p>
</form>
<div id="d0"></div>

今日のカラー占い

お好みの色をお選びください。

黄色

0 コメント:

コメントを投稿