Home > database >  How can I get the value of checked (checkbox) and autocomplete a textInput in react native
How can I get the value of checked (checkbox) and autocomplete a textInput in react native

Time:07-24

could you help me?, I'm developing with react native and typescript, I need to do this: I have a checkBox that tells the user to check if his name is the same as his credit card, if he clicks the checkbox, a TextInput with his name is autocompleted, if you don't click the checkbox that he can type his name. I have a variable like: user_name I don't have code because I don't know how to do it, but I think it goes something like this:

 const [checked, setChecked] = useState(false)
...
return(
            <CheckBox
              checked={setChecked}
              onPress={}
              checkedIcon='dot-circle-o'
              uncheckedIcon='circle-o'
              checkedColor='blue'
              uncheckedColor='blue'
            />


        <TextInput
          placeholder='Nombre completo'
          value={}
          onChangeText={}
)

CodePudding user response:

We could implement this as follows under the assumption that the name of the credit card is available. Let us call it creditCardName.

My example uses react-native-checkbox and the standard TextInput component. If you are using a different component, then the overall pattern still stays the same.

const [isChecked, setChecked] = useState(false);
const [userName, setUserName] = useState('');

return (
    <CheckBox
        value={isChecked}
        onPress={(newVal) => setChecked(newVal)}
     />
     <TextInput
       editable={!isChecked}
       placeholder='Nombre completo'
       value={isChecked ? creditCardName : userName}
       onChangeText={setUserName}
     />
)

The key-parts are as follows:

  1. Let the TextInput be editable if and only if isChecked is false, that is the CheckBox is unchecked.
  2. Let value of the TextInput be the creditCardName if the CheckBox is checked and set it to the userName otherwise.

CodePudding user response:

This code should work (run the snippet for demonstration)

const checkbox = document.getElementById('checkBox')
var input = document.createElement('input')
var submit = document.querySelector("#submit")
var name = "Tom"

checkbox.addEventListener('change', (event) => {
  if (event.currentTarget.checked) {
    document.querySelector("body").appendChild(input)
    input.value = name
  } else {
    input.parentNode.removeChild(input)
    input.value = ""
  }
})

submit.onclick = function() {
  console.log(input.value)
}
<input type="checkbox" id="checkBox">
<button id="submit">Submit</button>

  • Related