ENGR024
ENGR024

Reputation: 317

Radio buttons checked by default

I have an html page with a form in it. It has two radio buttons labelled Day Shift and Night Shift. I have a JavaScript IF else statement that says if the current time is later than 7:00 and before 19:00 then auto-default the dayshift button to be checked else check the Night Shift button.

I don't understand how to have the radio buttons be checked based off this statement. I have put a value into a JavaScript variable before from a radio button, but not the other way around. Any help is most appreciated.

html

<!DOCTYPE html>
<html>
   <head>
      <meta charset="UTF-8" content="HTML,CSS,XML,JavaScript">
      <script src="Scripts/autoRadio.js" type="text/javascript"></script>
      <link rel="stylesheet" type="text/css" href="Styles/Design.css">
   </head>
   <body>
      <form action="WasteEntry.asp" method="post">
         <fieldset>
            <input type="radio" required name="Shift" id="dayShift" value="Day Shift" >
            <input type="radio"  name="Shift" id="eveningShift" value="Evening Shift" >
         </fieldset>
      </form>
   </body>
</html>

JavaScript

 var now = new Date().getHours();
if (now > 7 && now < 19) {
     document.getElementById('dayShift').checked = true;
} else {
     document.getElementById('eveningShift').checked = true;
}

Upvotes: 0

Views: 537

Answers (2)

meskobalazs
meskobalazs

Reputation: 16041

You can do the following:

var now = new Date().getHours();
if (now > 7 && now < 19) {
     document.getElementById('dayShift').checked = true;
} else {
     document.getElementById('eveningShift').checked = true;
}

PS: You really should change the invalid duplicate IDs. And the required attribute should not be duplicated either.

Upvotes: 2

Bill Kindig
Bill Kindig

Reputation: 3622

This should do it.

var now= new Date().getHours();
if(now>7 && now<19){
    radiobtn = document.getElementById("dayShift");
    radiobtn.checked = true;
} else{
    radiobtn = document.getElementById("eveningShift");
    radiobtn.checked = true; 
}

Upvotes: 5

Related Questions