Skip to content

Instantly share code, notes, and snippets.

@chikoski
Created October 23, 2013 11:09
Show Gist options
  • Save chikoski/7116693 to your computer and use it in GitHub Desktop.
Save chikoski/7116693 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<h2>偶数を探します</h2>
<p>1から入力された数までの間にある偶数をすべて列挙します。</p>
<form id="input_form">
<label for="input">正の数を入力してください</label>
<input type="text" id="input">
<input type="button" id="start_btn" value="検索開始">
</form>
<div>
<h3>結果</h3>
<p id="result">まだ検索されていません。</p>
</div>
</body>
</html>
var isEvenNumber = function(num){
num = Number(num);
return num % 2 === 0;
};
var showMessage = function(messageType){
var r = document.getElementById("result");
if(r !== null){
if(messageType == "NO_EVEN_NUMBER"){
r.innerHTML = "偶数は一つもありませんでした。";
}else if(messageType == "INVALID_INPUT"){
r.innerHTML = "正の数を入力してください";
}else if(messageType == "RESET"){
r.innerHTML = "";
}
}
};
var resetResult = function(){
showMessage("RESET");
};
var appendIfEvenNumber = function(num){
if(isEvenNumber(num)){
var r = document.getElementById("result");
if(r !== null){
r.innerHTML += num + "<br>";
}
}
};
var doListEvenNumbers = function(ub){
resetResult();
var i = 1;
while(i < ub){
appendIfEvenNumber(i);
i = i + 1;
}
};
var listEvenNumbers = function(){
var input = document.getElementById("input");
if(input !== null){
var upper_bound = Number(input.value);
if(!isNaN(upper_bound) && upper_bound > 0){
doListEvenNumbers(upper_bound);
}else{
showMessage("INVALID_INPUT");
}
}
};
var btn = document.getElementById("start_btn");
if(btn !== null){
btn.onclick = listEvenNumbers;
}
var input = document.getElementById("input_form");
if(input !== null){
input.onsubmit = function(event){
return false;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment