Home > Software design >  How to make checkbox true when input is a number
How to make checkbox true when input is a number

Time:08-04

I'm struggling with this challenge for a long time. Any help would be appreciated. I want to do this: if input has number then checkbox => true if input has letters then checkbox => true

CodePudding user response:

It's hard to give you a good answer with the information you have provided, however. If you want to check if the content of the input contains letters or numbers the best approach would be to add a onchange event listener to the input, where you pass the content through a regex like so:

/^[\da-zA-Z]*$/g.test(input.value)

Or, if you also want to check for spaces use this regex:

/^[\da-zA-Z\s]*$/g.test(input.value)

If that returns true, then just set the checkbox to checked

CodePudding user response:

Use state to maintain the input value, and have the checkbox call a function that tests whether the value contains only letters or numbers.

const { useState } = React;

function Example() {

  const [ input, setInput ] = useState('');

  // When the input changes update the state
  function handleInput(e) {
    const { value } = e.target;
    setInput(value);
  }

  // Does the input value contain any
  // letters or numbers?
  function checkInput() {
    return /^[a-zA-Z0-9] $/.test(input);
  }

  // `checkInput` returns a boolean that sets
  // the value of the checkbox
  return (
    <div>
      <input type="text" onInput={handleInput} />
      <input type="checkbox" checked={checkInput()} />
    </div>
  );

}

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>

  • Related