1

I have an input field currency that is disabled if the value on another field fee is empty or zero.

Html

Fee: <input id="fee"><br>
Currency: <input id="currency"><br>

Javascript

$("#fee").on('input', function() {
$('#currency').prop('disabled', (this.value === '0' || this.value === ''));  
})
.trigger('input');

or JSFiddle

What I now try to achieve is that the field currency is also disabled if someone enters 00 or 0.0 or 0,0 which currently is not the case. I have to test for both a . and a , in my field, because users can enter numbers with both values as a delimiter.

I through of changing this.value === '0' to this.value < '0.000000001' || this.value < '0,000000001', but then it still won't work with 00. Also something like 0,1 will be disabled (which it shouldn't), and that is because of the comma , which does not work in a number?

Is there perhaps an easy (or difficult) solution to my problem?

edit to clarify: the field currency should be disabled when the user enters 0, 00 (or any number of zeros), 0.0(or any more zeros) and 0,0(or any more zeros). The field should be enabled if the user enters something like 09 or 0,5 or 0.1.

Dirk J. Faber
  • 4,360
  • 5
  • 20
  • 58
  • Can you clarify what are the expected valid values or rather only which values are invalid. An if/else condition would suffice in the above case. if not a regular expression would work. – Abdul Rehman Jul 29 '18 at 15:16
  • @Bsienn I made an edit to clarify. Hope it is clear like this. – Dirk J. Faber Jul 29 '18 at 15:19
  • Possible duplicate of [validation if value is empty or zero ('0'), but what if it's "0.0"](https://stackoverflow.com/questions/31566870/validation-if-value-is-empty-or-zero-0-but-what-if-its-0-0) – Heretic Monkey Jul 29 '18 at 15:22

2 Answers2

3

I suggest you to work a little on the input value prior to compare it.

  1. replace coma by dot (if any)
  2. convert to a float number

So now, there are two possibilities, you have a valid float number or a NAN (not A Number). The second case is easy to determine using isNaN() which returns a boolean.

$("#fee").on('input', function() {

  // Replace all coma by dot and parse as a float number
  var value = parseFloat(this.value.replace(",","."));

  $('#currency').prop('disabled', ( value === 0 || isNaN(value) ));  
})
.trigger('input');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Fee: <input id="fee"><br>
Currency: <input id="currency"><br>
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
1

You can use this.value.replace(/[0+.,]+/,'') == 0

 $("#fee").on('input', function() {
   $('#currency').prop('disabled', (this.value.replace(/[0\+\.,]+/,'') == 0));  
  }).trigger('input');