Skip to content

Instantly share code, notes, and snippets.

@chikoski
Created November 5, 2013 12:00
Show Gist options
  • Select an option

  • Save chikoski/7318047 to your computer and use it in GitHub Desktop.

Select an option

Save chikoski/7318047 to your computer and use it in GitHub Desktop.
.hidden{
display: none;
}
.visible{
display: inline;
background-color: #f99;
padding: 4px 1em;
color: #333;
}
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<div>
<input type="text" id="name">
<button id="btn">追加</button>
<p id="error" class="hidden">その名前は既に存在します</p>
</div>
<ul id="list"></ul>
</body>
</html>
(function(){
Array.prototype.indexOf = Array.prototype.indexOf ||
function(item){
var i = 0;
while(i < this.length){
if(item == this[i]){
return i;
}
i = i + 1;
}
return -1;
};
Array.prototype.exists = Array.prototype.exists ||
function(item){
return this.indexOf(item) >= 0;
};
var nameList = [];
var view ={
btn: document.getElementById("btn"),
input: document.getElementById("name"),
list: document.getElementById("list"),
error: document.getElementById("error")
};
nameList.render = function(list){
view.list.innerHTML = "<li>" + this.join("</li><li>") + "</li>";
};
view.showErrorMessage = function(){
this.error.setAttribute("class", "visible");
};
view.hideErrorMessage = function(){
this.error.setAttribute("class", "hidden");
};
view.btn.onclick = function(){
view.hideErrorMessage();
if(!nameList.exists(view.input.value)){
nameList.push(view.input.value);
nameList.render(list);
}else{
view.showErrorMessage();
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment