Eightleven Eightleven - 4 months ago 6
jQuery Question

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

Answer

$(document).ready(function(){
    var money = 20;
    $("#nominal").change(function() { // take change event of input box
       if ($(this).val() == money )  { // use $(this) to take value
          var h = document.createElement("H1"); // Create a <h1> element
          var t = document.createTextNode("Thank You"); // Create a text node
          h.appendChild(t);      
          $('form').append(h); // append created h1 element in form/html
       } else {
          $('form').find("h1").remove();
       }
     })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form method="post" action="">
<input type="text" id="nominal" value="">
<input type="button" value="submit" name="submit" id="submit">
</form>

Comments