简体   繁体   中英

Radio buttons checked by default

I have an html page with a form in it. It has two radio buttons labeled 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;
}

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; 
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM