Search code examples
javascriptform-submitshort-circuiting

Enable submit button only when no error is found


I have a simple application in which I only want to enable the calculate button only when no-errors are found (an error is recorded if the value is not a number, or a value is less than 0). I perform a few conditional checks using && and || operator. However, when only one input has been filled properly, without errors, the button is enabled. But, when an explicit wrong value has been specified the button is disabled again.

Code: https://github.com/KaustubhMaladkar/Tip-Calculator

    if (!peopleError && !billError) {       
      submit.removeAttribute("disabled");
    }
    if (billError || peopleError) submit.setAttribute("disabled", "")

Live site: https://kaustubhmaladkar.github.io/Tip-Calculator/


Solution

  • I would like to thank that @Nestoro for their comments on my question as most, if not all, of my answer is based their comments.

    This code will solve the problem

    if (!peopleError && !billError && Number(billElem.value) && Number(peopleElem.value)) submit.removeAttribute("disabled");
    else submit.setAttribute("disabled", "");