0

Can I have two values in checkbox. Normally if I assign single value to checkbox, whenever I check or uncheck this checkbox it return me value, but I want this behavior only if I check the value(eventually alternative behavior). I tried this way, but it didn't work

<input type="checkbox" name="path" id="path" defaultChecked={true} 
       value={ this.checked ?userData.image : ''} onChange={onChangeText}/>

Ofcourse I can do it in onChange function, but I want to find more simple and 'aesthetic' way, without

getElementById or e.target.name== ? something() : somethingElse()

And I want to do it in React.

Wiktor Kujawa
  • 595
  • 4
  • 21
  • https://stackoverflow.com/questions/29264619/html-submit-multiple-values-through-one-check-box/29265261 You may get some clues from here –  Aug 24 '20 at 19:41
  • I did that before and probably will stay with it, because that looks that I can't do it this way and this trick with hidden checkbox doesn't work in React. – Wiktor Kujawa Aug 24 '20 at 19:57
  • Please add more detail so we can understand what you are trying to do. Specifically, make a more complete example. The first example is incomplete because `this.checked` is undefined. (You probably should be using `this.state.checked` instead anyway.) Your second code snippet has syntax errors. – Code-Apprentice Aug 24 '20 at 20:24

2 Answers2

0

When you're saying you want a more simple and 'aesthetic' way, you are actually thinking to difficult. I would stick with an onchange function as it improves readability in your code, which also is easier to track down when coming back at a later date.

0

You. can simply move the turnery operator for value to onChange method as follow.

<input type="checkbox" name="path" id="path" defaultChecked={true} 
       onChange={(event) => onChangeText(event.target.checked ? userData.image : '')}/>
Ashish Patel
  • 317
  • 1
  • 8