Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if input value equals specific text, display div

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>
like image 949
user3367388 Avatar asked Jan 27 '26 18:01

user3367388


2 Answers

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");
    });
});
like image 162
Pranav C Balan Avatar answered Jan 29 '26 08:01

Pranav C Balan


do this changes to your code

  • add val() for getting value of an element
  • use == operator in condition
  • for comparing string you should add quotes like "Kasey"

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>
like image 32
chriz Avatar answered Jan 29 '26 09:01

chriz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!