user4759415
user4759415

Reputation:

How to check contents of input in "real time"

I'm working on a web form and it's been set up with a text field to receive what is expected to be a numeric value. The form won't submit if the contents of this field aren't numeric but there was no error message put in place to let the user know that they filled this field out wrong.

My question is...is there a way in real time to check what's in the input and do something to tell the user they aren't filling it out properly? If everything is ok I want the border of the input to be green, if not then make the border red and change the default text of the input to tell them we only want numbers.

This is loosely what I've got so far as my starting point...

HTML:

<input type="text" class="btn-blue" id="testing"></input>

JS:

$('#testing').attr('placeholder', 'Enter Amount');
var useramount = $("#testing").val();
if (useramount.match(/^\d+$/)) {
   $("#testing").css({border: "2px solid #33CC00 !important"});
} 
else {
  $("#testing").css({border: "2px solid #FF0000 !important"});
  $("#testing").innerHTML = "";
  $('#testing').attr('placeholder', 'Only Numbers Please');
}

I've borrowed the basic principle of the validation from this previously asked question: Check If only numeric values were entered in input. (jQuery)

Any help is greatly appreciated.

Upvotes: 7

Views: 19387

Answers (5)

Thomas Bui
Thomas Bui

Reputation: 308

Example for me using the vanilla javascript.
I write this to disable the Submit button whenever no text value

let textInput = document.getElementById('dataInput') // take the element value
  textInput.addEventListener('input', (test) => { //whenever event input happend
  console.log("text", textInput.value)
    if (textInput.value.length !== 0) {
      document.getElementById('btnSubmit').classList.remove('disabled')
//remove the class disabled in submit button
    } else {
      document.getElementById('btnSubmit').classList.add('disabled')
    }
  })

Upvotes: 2

Jon Koops
Jon Koops

Reputation: 9261

You can use the input event to get changes when the user is typing inside of the field. On the change event you will be given the element corresponding to the input element the event listener is attached to as event.target. Using this reference you are able to get the value of the input by using the value property on the element.

After you have retrieved the value you will need to verify that it is in fact numerical. Thankfully jQuery provides a method called isNumeric that allows us to do just that.

Once we've established the fact that the value is indeed numerical you can either apply a class or just set the style to what you want to be. Make sure you also check if the value has been emptied so the user does not get confused.

As for the validation message - it's not a good idea to set the value of the input as the user is interacting with said element. Instead I've chosen to add textual element to represent the message that will be shown conditionally based on the validation state.

// Add error message element after input.
$('#some-number').after('<span class="error-message">Please enter numbers only!</span>')

$('#some-number').on('input', function (evt) {
  var value = evt.target.value
  
  if (value.length === 0) {
    evt.target.className = ''
    return
  }

  if ($.isNumeric(value)) {
    evt.target.className = 'valid'
  } else {
    evt.target.className = 'invalid'
  }
})
input {
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  outline: none;
  border: 1px solid black;
}

input.valid {
  border: 1px solid green;
}

input.invalid {
  border: 1px solid red;
}

input.invalid + .error-message {
  display: initial;
}

.error-message {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="some-number">

Upvotes: 5

DefaultError
DefaultError

Reputation: 316

You could bind your validation logic to a keypress event like

$('#target').keydown(function () {
    // validation
});

or

$("#target").blur(function() {
    // validation
});

Example:

https://jsfiddle.net/smzob72e/

Upvotes: 2

Dan Chaltiel
Dan Chaltiel

Reputation: 8484

I'd use a Jquery on("input") like this :

$(document).ready(function() {
    $('#testing')
    .attr('placeholder', 'Enter Amount')
    .on("input", function(){
        var $this = $(this);
        var useramount = $this.val();  
        if($.isNumeric(useramount)){
            $this.css("border", "2px solid green !important");
            $this.css("background", "green");
        } else {
            $this.css("border", "2px solid red !important");
            $this.css("background", "red");
            $this.val("");
            $this.attr('placeholder', 'Only Numbers Please');
        }
    });
});

The background field is more obviously shown than the border, for educational purpose.

Upvotes: 0

user4490434
user4490434

Reputation:

You can do this with the onkeypress Event. Every time the user presses a key while the input box is selected, update the input's value.

Example:

var input = document.getElementById("input-box");
var inputValue = document.getElementById("input-box").value;

input.addEventListener("keypress", function() {
  inputValue = document.getElementById("input-box").value;
  // do something with it
});
<input id="input-box"/>

I hope I didn't get anything wrong.

Upvotes: 5

Related Questions