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>
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");
}
});
});
FIDDLE
UPADATE :
You can simplify the code as follows
$(document).ready(function () {
$("#fname").keyup(function () {
$("#pete").css("display", this.value == "Kasey" ? "block" : "none");
});
});
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With