最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to check contents of input in "real time" - Stack Overflow

programmeradmin7浏览0评论

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.

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.

Share Improve this question edited May 23, 2017 at 12:10 CommunityBot 11 silver badge asked Mar 27, 2017 at 15:15 user4759415user4759415 2
  • I know it is unrelated to your question - but have you considered using type="number"? – Jon Koops Commented Mar 27, 2017 at 15:17
  • Yes - unfortunately the form is already built and was done by another developer and the portion of the CMS that generates forms doesn't allow you to specify what type of input you want. It just spits out a generic input field. – user4759415 Commented Mar 27, 2017 at 15:20
Add a ment  | 

5 Answers 5

Reset to default 5

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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="some-number">

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.

You could bind your validation logic to a keypress event like

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

or

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

Example:

https://jsfiddle/smzob72e/

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')
    }
  })

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.

发布评论

评论列表(0)

  1. 暂无评论