user4826575
user4826575

Reputation: 11

Have a button listen to radio inputs

I have a button that is created using javascript:

<button id="connectbutton" onclick="start()">Refresh Data</button>

Next, I have these radio buttons as well:

<input type="radio" name="args" value="Heat">Set thermostat mode to HEAT.<br>
<input type="radio" name="args" value="Off">Set thermostat mode to OFF.<br>
<input type="radio" name="args" value="Cool">Set thermostat mode to COOL.<br>
<input type="radio" name="args" value="REDALERT">Set thermostat mode to RED  ALERT.<br> 
<input type="submit" value="Do it!">

Is there a way to have the radio types listen to the button. Basically, if I select a mode, and press refresh data it should do it in whatever I have programmed for that mode.

Upvotes: 0

Views: 77

Answers (1)

Justin Beck
Justin Beck

Reputation: 91

In your start function you can do something like

var argSelected = document.querySelector('input[name="args"]:checked').value;

or if using jQuery

var argSelected = $('input[name="args"]:checked').val();

Then use a switch to select the code you want to run for each selection.

switch(argSelected) {
  case Heat:
    /**Do heat thing**/
    break;
  case Off:
    /**Do off thing**/
    break;
  case Cool:
    /**Do cool thing**/
    break;
  case REDALERT:
    /**Do REDALERT thing**/
    break;
  default:
    /**Nothing selected**/
    alert('No radio button selected');
    break;
}

Upvotes: 1

Related Questions