I’m trying to run this script many times but it only works twice.
What it’s supposed to do is ..Type a city name in the text box and then submit it and a function occurs. but it only works twice
$("#b").click(function() {
var password = "toronto";
if ($("#pass").val() == password) {
$(".tim1").css({
"display": "block"
});
return true;
}
});
$("#b").click(function() {
var password = "ottawa";
if ($("#pass").val() == password) {
$(".tim2").css({
"display": "block"
});
return true;
}
});
body {
background-color: #6A6A6A;
}
.tim1 {
background-color: #000000;
position: absolute;
top: 40px;
left: 10px;
width: 100px;
height: 100px;
display: none;
}
.tim2 {
background-color: #525119;
position: absolute;
top: 40px;
left: 10px;
width: 100px;
height: 100px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="pass"> <input type="button" id="b" value="Guess">
<div class="tim1"></div>
<div class="tim2"></div>
2
Answers
You’ve assigned two click handlers to
#b
, this maybe a source of your frustrations. You can combine them with a simpleelse-if
:The code "works", but you’ve styled two elements to occupy the exact same space at the same time. You probably want to hide them when performing the operation again.
You can also simplify the operation. There’s no need to attach multiple click handlers here. All you need is a click handler which:
For example: