0

I have this function where if the textbox has a value of 0 the checkbox will be set to true. But I have this weird scenario where if the textbox is blank or greater than 0 I need the checkbox to be false

When I debug true this seems to be "" and 0 are the same thing Does anyone know how I would go about making this work?

$(document).on('blur change keyup', '.CostInput', function () {
  if ($(this).val() == 0) {
    $('input#Enquiry_Cost_InputFree_0').prop('checked', true);
  }

  if ($(this).val() > 0 || "") {
    $('input#Enquiry_Cost_InputFree_0').prop('checked', false);
  }
});

And I have created a JS fiddle = https://jsfiddle.net/barrycorrigan/Lqxuvr4w/9/

2
  • 1
    Well, there is a difference between == and === ... stackoverflow.com/a/523647/9741277
    – leun4m
    Commented Sep 21, 2020 at 14:57
  • Have an exe on your expression: $(this).val() > 0 || "" you probably mean to say: $(this).val() > 0 || $(this).val() === ""
    – leun4m
    Commented Sep 21, 2020 at 15:04

1 Answer 1

1

There is a difference between == and === in JavaScript.

0 == ""  // => true
0 === "" // => false

You probably mean to say:

$(document).on('blur change keyup', '.CostInput', function () {
  let val = $(this).val();

  if (+val === 0) {
    $('input#Enquiry_Cost_InputFree_0').prop('checked', true);
  }

  if (+val > 0 || val === "") {
    $('input#Enquiry_Cost_InputFree_0').prop('checked', false);
  }
});

For more information on how it works, see here: https://stackoverflow.com/a/359509/9741277

3
  • Thanks for the update @leun4m but from your example in the text box if I enter the value 0 it doesn't populate the checkbox to true Commented Sep 21, 2020 at 15:13
  • Oh, sorry my mistake. Didn't test it. Since the textbox contains contains the value as string you need to convert it to a number type if you compare it with numeric values. Using +val should be safe -- even when val is not a number, because NaN === 0 and NaN > 0 will always return false.
    – leun4m
    Commented Sep 21, 2020 at 15:25
  • Cheers thats much better than the solution I had which was adding "0" around the first if statement which worked but I guess it would have been buggy jsfiddle.net/barrycorrigan/Lqxuvr4w/11 Commented Sep 21, 2020 at 15:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.