user3367388
user3367388

Reputation: 39

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>

Upvotes: 3

Views: 27684

Answers (3)

Pranav C Balan
Pranav C Balan

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");
        }
    });
});

FIDDLE

UPADATE :

You can simplify the code as follows

$(document).ready(function () {
    $("#fname").keyup(function () {
        $("#pete").css("display", this.value == "Kasey" ? "block" : "none");
    });
});

Upvotes: 8

khaos337
khaos337

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

chriz
chriz

Reputation: 1345

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>

Upvotes: 4

Related Questions