Search code examples
javascriptjqueryhtmldomuser-input

Javascript function to show text if i input value


To the point, if i input value "20" in input field then show message "Thank you".

Here's my HTML Code:

<form method="post" action="">
<input type="text" id="nominal" value="">
<input type="submit" value="submit">
</form>

Here's my JS Code:

$(document).ready(function(){

    var money = 20;

    /* not sure if this is written correctly, but this is supposed to
    check whether the hidden input element value is equal to var money */

    if ($("input[id='nominal']").val() == money )  {

     var h = document.createElement("H1")                // Create a <h1> element
     var t = document.createTextNode("Thank You");     // Create a text node
     h.appendChild(t);                                   // Append the text to <h1>

    };
});

i've created one script to fulfill what I need, but not working! what's wrong?

My JDFIDDLE LINK


Solution

  • You have to create an event to listening for changes, in this case changed. And you can make your code a bit smaller too. ;)

    $(function() {
        $("#nominal").change(function() {
            if( $(this).val() == 20 )
                $(this).after("<h1>Thank You</h1>");
        });
    });
    

    Full working exaple with removing the message when value changes again and strict check can be seen here.