Skip to content

Instantly share code, notes, and snippets.

@chikoski
Created October 31, 2013 03:38
Show Gist options
  • Select an option

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

Select an option

Save chikoski/7244061 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>
var nameList = [];
var btn = document.getElementById("btn");
var input = document.getElementById("name");
var list = document.getElementById("list");
var error = document.getElementById("error");
var showNameList = function(list){
list.innerHTML = "<li>" + nameList.join("</li><li>") + "</li>";
};
var indexOf = function(name){
var i = 0;
while(i < nameList.length){
if(name == nameList[i]){
return i;
}
i = i + 1;
}
return -1;
};
var exists = function(name){
return indexOf(name) >= 0;
};
var showErrorMessage = function(){
error.setAttribute("class", "visible");
};
var hideErrorMessage = function(){
error.setAttribute("class", "hidden");
};
btn.onclick = function(){
hideErrorMessage();
if(!exists(input.value)){
nameList.push(input.value);
showNameList(list);
}else{
showErrorMessage();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment