2

How do I get the value a user selects in a radio button group? Here is a simple code, what should I add in order to be able to retrieve the user selection? I couldn't find it in the docs.

view [
    radio "First"
    radio "Second"
    radio "Third"
]
draegtun
  • 22,441
  • 5
  • 48
  • 71
SoleSoul
  • 368
  • 2
  • 14

3 Answers3

4

In R3GUI radio buttons are grouped by proximity, and you can get their values by naming each button.

view [ 
   r1: radio "one"
   r2: radio "two"
   r3: radio "three"
   button "show" on-action [ print get-face reduce [ r1 r2 r3 ]]
]

You should use get-face and avoid looking at the internals when it's supported.

Graham Chiu
  • 4,856
  • 1
  • 23
  • 41
  • What if I have many radio buttons, each one represents a word. Do I have to determine where the "true" is in the list of booleans and match the word to where I found it? Wouldn't it be better to use the first answer by sqlab to simply set a variable to the word I need? – SoleSoul Sep 02 '13 at 21:22
  • If they're grouped by proximity, why do you need to name each of them? – rgchris Sep 02 '13 at 21:38
  • It depends on what you want to do. If you are using the radio buttons to set a flag in a form, and then process the form, then setting another flag seems redundant since the state is already captured. But if you want to dynamically do something based on selection, then use the on-action block. You don't need to name them, but by doing so you can then use 'get-face more easily. Otherwise you're going to have to navigate to whatever container holds the radio buttons and iterate thru them. – Graham Chiu Sep 02 '13 at 23:30
  • I do need a selection which fits the first case, but I don't need it as 'true' or 'false' but as one of many possible strings. Why bother getting a list of booleans when I can get the selected string directly? – SoleSoul Sep 03 '13 at 07:16
2

probably not the only way, but you can set an external variable, as in

x: 0  
view [
  radio "First" on-action [set 'x 1]
  radio "Second" on-action [set 'x   2]
  radio "Third" on-action [set 'x 3]
]
print x
sqlab
  • 6,412
  • 1
  • 14
  • 29
  • I like this answer more because you can decide on a custom value and you don't have to add code after the view part in order to get the value. – SoleSoul Sep 02 '13 at 17:52
  • Except the question is to get the value of the radio button :) An external value could be set by other functions. – Graham Chiu Sep 02 '13 at 20:05
2

An other way

view [
  r1: radio "First"
  r2: radio "Second"
  r3: radio "Third"
]
print r1/state/value
print r2/state/value
print r3/state/value
sqlab
  • 6,412
  • 1
  • 14
  • 29