Reputation: 39
I'm learning jQuery slowly but surely, so please excuse my ignorance. I did a lot of googling that resulted in the Frankenstein example below.
In this example, if the user enters "Kasey" into the input
, I would like div#pete to have display:block
.
Thanks in advance!
<!DOCTYPE html>
<html>
<head>
<script>
$(document).ready(function(){
var val = $("#fname").length;
if (val = Kasey) {
$("#pete").css("display", "block");
}
</script>
</head>
<body>
<p>Name: <input type="text" id="fname"></p>
<p id="pete" style="display:none;" >Pete</p>
</body>
</html>
Upvotes: 3
Views: 27684
Reputation: 115232
You can use keyup()
handler to listen keyup
event. Inside that use this.value
to get the value
$(document).ready(function() {
$("#fname").keyup(function() {
if (this.value == "Kasey") {
$("#pete").css("display", "block");
}
else {
$("#pete").css("display", "none");
}
});
});
UPADATE :
You can simplify the code as follows
$(document).ready(function () {
$("#fname").keyup(function () {
$("#pete").css("display", this.value == "Kasey" ? "block" : "none");
});
});
Upvotes: 8
Reputation: 636
The problem is that your function is reading the value of fname when the document loads and not after the user input. Also, you are assigning the length to val when you should be assigning the value
var val = $("#fname").val();
Lastly your if statement needs the is equal to operator with is ==
if (val == 'Kasey')
Upvotes: 1
Reputation: 1345
do this changes to your code
val()
for getting value of an element==
operator in condition Note : if u want do this on form load code like follows or add keyup()
event
<script>
$(document).ready(function(){
var val = $("#fname").val();
if (val == 'Kasey') {
$("#pete").css("display", "block");
}
});
</script>
Upvotes: 4