0

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.

StefanM
  • 797
  • 1
  • 10
  • 17
  • Are you saying you just need to get the value of the currently selected radio button whenever you click the `Refresh Data` button, so that you can use it in your code to perform some corresponding function? – Jonathan Bowman Oct 31 '16 at 14:13
  • 2
    if you want something to happen when the button is pressed then you need to listen for a button press, you do not need the radio buttons to listen to anything. you already have an onlick listener on the button, so just add some code to the `start()` function to determine which raddio button is pressed and act accordingly. – I wrestled a bear once. Oct 31 '16 at 14:14
  • Possible duplicate of [How can I check whether a radio button is selected with JavaScript?](http://stackoverflow.com/questions/1423777/how-can-i-check-whether-a-radio-button-is-selected-with-javascript) – I wrestled a bear once. Oct 31 '16 at 14:15
  • It looks like, you could read the value of your radioselect in your start() function and switch based on that value, to your code for the right mode. – sebkrueger Oct 31 '16 at 14:15

1 Answers1

1

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;
}
  • So, just a question, can I define start() as something. Like how would I put var argSelected in the start when its only present in the button id line? – user4826575 Oct 31 '16 at 16:55
  • In the line, onclick="start()" start() refers to the function named "start" in your .js file. When the button is clicked it runs the function. You may want to take a quick javascript course at codecademy or other such online source. They usually have a free one that will give you some insight as to how javascript works. – Justin Beck Oct 31 '16 at 20:39