John Moore John Moore - 1 year ago 80
Javascript Question

Display Notice if Form Contains Word

Im looking to display a notice if a user types a specific combination of numbers into a text field without them having to submit the form.

Ex: If user types 1234 or 7890 into Field #ExampleField1, the page will display the div #ExampleDiv1

I've found tons of form validation examples that happen on submit but not live.

Answer Source

This shows you how to show/hide an element based on text input.
I used regular expressions for efficiency and clarity. I also tested my regular expressions here.

//Shorthand for $(document).ready();
$(function() {
  //The numbers to search for in the string.
  var numRegEx = /(4486|4716|5568)/;
  var msg = $('#msg');
  //Hide the message on load.
  var txt = $('#txt');
  //Wire up the keyup event listener
    var val = $(this).val();
    Using regular expressions is the most efficient way to do this.
    You can check for additional numbers above by modifying 
    the regular expression.
    if (numRegEx.test(val)) {;
    } else {
<script src=""></script>
<label for="txt">Try entering text that contains 4486 OR 4716 OR 5568</label>
<input type="text" id="txt" placeholder="Enter text here..." />
<div id="msg">
  <b>Hello, world!</b>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download