0

This is my code,how can i check entered number is multiples of hundred,

$("#input1").keyup(function() {
  var value = $(this).val();
  var value1 = $(this).val() * 0.1;
  var value2 = Math.round(value1);


  ($("#log,#log1").text(value));
  $("#percentage1").text(value2);
}).keyup();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="col-md-6 redeem_input" type="text" name="enter_amt" id="input1" maxlength="5" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" placeholder="Min 100 and Max 10000">
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
nijam
  • 1
  • 2

1 Answers1

0

Inputs return values that are strings. You need to use parseInt() to convert it to a number if you want to use it for math.

String.prototype.toInt = function() { return parseInt(this, 10); };

$(".input")
  .on('keyup', function() {
    this.value = this.value.replace(/[^0-9]/g, '');

    if (this.value && this.value.toInt() >= 100) {
        $('.output').text(`is ${this.value.toInt() % 100 ? 'not' : ''} a multiple of 100.`);
    } else {
        $('.output').text('Enter a number between 100 and 10000.');
    }
}).keyup();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="input" type="text" maxlength="5">
<p class="output"></p>

Whats going on

String.prototype.toInt - add a method to the String object for converting to a number. You can just use the native parseInt("number", base), but I think this makes the code more readable.

this.value = this.value.replace(/[^0-9]/g, '') - a lazy validation to make sure you only get numbers. I recommend using keydown for validation, but that requires mode code.

if (this.value && this.value.toInt() >= 100) - make sure there's a value and that it's greater than or equal to 100

`is ${} a multiple of 100` - the backtick allows you to put code enclosed within ${} inline with text. Search template literal for more on that.

this.value.toInt() % 100 ? 'not' : '' - This is an inline if statement (statement ? true part : false part) saying that if the value entered mod 100 is 0, which means it is a whole multiple, no remainder, and which javascript will coerce to false, add a empty string, else add the word "not". Search modulus and ternary operator for more on those.

Just my opinion

I would try to not use variables when possible. And when you do use them, be sure the name is highly descriptive to the data it's storing. Trying to remember what value1 and value2 represent when you get into more complex code isn't very productive.

Community
  • 1
  • 1
PoorlyWrittenCode
  • 1,003
  • 1
  • 7
  • 10