0

I am trying to extract the call to replace commas into a reusable function but I have been unsuccessful.

if (Number($amountField.val().replace(/,/g, '')) > 0 || Number($prorationOwedField.val().replace(/,/g, '') > 0)) {
   $taxField.prop('disabled', false);
}
Studocwho
  • 2,404
  • 3
  • 23
  • 29
Johans
  • 5
  • 4
  • I dont understand. your function is an if statement, that disables what seems to be another field. what do you mean by replace commas – jstuartmilne Oct 22 '19 at 19:28
  • if the amountField & prorationOwedfield is greater than 0, the tax field enables. I am using .replace(/,/g, '') often in my code and I was wondering if i could extrac it in a function. Hope that is clearer – Johans Oct 22 '19 at 19:37
  • https://stackoverflow.com/questions/30343179/how-to-convert-a-number-with-comma-as-string-into-float-number-in-javascript – Ted Fitzpatrick Oct 22 '19 at 19:42

2 Answers2

0

How about this

  function noCommas(fieldID){
    return Number($(fieldID).val().replace(',', '')) > 0
  }

Here is a working fiddle : https://jsfiddle.net/sudakatux/3vLnhjs4/11/

Basically you just pass the selector.

You can pass the field if you like

 function noCommas($justTheField){
    return Number($justTheField.val().replace(',', '')) > 0
  }

and youll use it the same way :

if(noCommas($amountField) || noCommas($prorationOwedField))
jstuartmilne
  • 4,398
  • 1
  • 20
  • 30
  • 1
    Thanks a lot, this is exactly what I needed!! A small correction for anyone's future reference, it worked with a $ sign inside => noCommas($justTheField) – Johans Oct 22 '19 at 20:06
0

I think i understand what you mean.

You can use a callback.


function execIfFieldsValidate(cb) {
    if (Number($amountField.val().replace(/,/g, '')) > 0 || Number($prorationOwedField.val().replace(/,/g, '') > 0)) {
        cb()
    }
}

// and this is how you can use it.
execIfFieldsValidate(() => {
    console.log("is validated")
})

Hope it can help you.

ogastonc
  • 36
  • 1
  • 5