简体   繁体   中英

check radio button in javascript

The default value of one on my radio boxes on my page is set to checked. I noticed that when I change the selection and reload the page, the check goes back to the default value. I was wondering whether there is a way in javascript to programatically set the value checked property of my radio elements.

This is my html

<body>
<TD><INPUT TYPE="radio" NAME="Performer" VALUE="Aitken"   >Aitken</TD>
  <TD><INPUT TYPE="radio" NAME="Performer" VALUE="Coltrane"  CHECKED>Coltrane</TD>
  <TD><INPUT TYPE="radio" NAME="Performer" VALUE="Julliard" >Julliard</TD>
  <TD><INPUT TYPE="radio" NAME="Performer" VALUE="Kronos"  >Kronos</TD>
  <TD><INPUT TYPE="radio" NAME="Performer" VALUE="Waits"  >Waits</TD>
<input type="submit" id="submit_button"name="sunmit">
</body>

Html, by nature, is stateless. Changing the value of something on a page does absolutely nothing, unless you actually do something with it.

In order to persist this value, you have to send it back to your server (either through AJAX, or a traditional form submit) and instead of having a hardcoded value, use a dynamic language of your choice.

You can also use local storage to have a javascript implementation that is specific to the user/machine.

You can set a cookie each time someone checks/unchecks that contains all checked elements, then re-check them based on the cookie data on page load.

But I wouldn't recommend it unless you know what you are doing as you will be jeopardizing usability when you do something "unexpected" with forms.

Once you know which button should be checked, using a cookie value or localStorage as other answers suggest, you can indeed check a button using javascript. Here is a jQuery snippet:

var valueToCheck = "Kronos";  // assume you have a known value like this one
$('input[name="Performer"][value="'+ valueToCheck +'"]').prop('checked', true);

If you do not have jQuery available you can use native code. Each input element has a value attribute and radio buttons also have a checked attribute:

var buttons = document.getElementsByTagName('input'), button;
for (var i = 0; i < buttons.length; i += 1) {
    button = buttons[i];
    if (button.name === "Performer" && button.value === valueToCheck) {
        button.checked = true;
        break;
    }
}

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