Skip to content
Advertisement

Disabling a button if an immutable list contains empty value

If a user enters a blank value in a textbox, the button should be disabled. I’m doing this check using the following filter.But this does not work.Please advice.

                   <ALink href='javascript:void(0);'
                    className='button primary default-size' id='globalParametersCancel'
                    content={localeHelper.translate('iaSampling.iaGlobalConfiguration.reset')}
                    isDisabled={(!this.globalParameterChanged) && (!this.gaparameterlist?.find(x => x.value == ' '))}
                    onClick={this.reset} />     

Advertisement

Answer

If you are using React you could do something like this, imagine you had an input field with an onChange. You can set the state in the change handler equal to e.target.value. When the state has changed, the useEffect() callback is called and will check if the input is valid. If the input is valid (you could do any validation you like, for example date, number, regular expression…), you set valid (setValid(true)).

// callback after setting text
useEffect(() => {
  // do validation
  if (text) {
    setValid(true);
  } else {
    setValid(false);
  }
}, [text]);

const handleChange = (e) => {
  e.preventDefault(); // prevent default action
  setText(e.target.value); // set text
};

Then, according to the valid boolean state value, you could render what you want, in this case a button, if not valid => display a message or whatever you like.

const validDisplay = valid ? (
  <button onClick={handleClick}>submit</button>
) : (
  <span>Not valid!</span>
);

This is what your final return could look like.

return (
  <div>
    <input value={text} onChange={handleChange}></input>
    <p>
      {validDisplay} {text}
    </p>
  </div>
);

I made a sandbox, you can try it out here

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement