user2065736
user2065736

Reputation:

Radio button's behaviour

Im a DOM/javascript newbie trying to get my basics right. I'm just trying to observe radio button's behavior on clicking it. Heres my code.

HTML

    <script src="tmp.js"></script>
    <input type="radio" id="inp1" name="same" onclick="show();"/>
    <input type="radio" id="inp2" name="same" onclick="show();"/>

JS (tmp.js)

   function show() {
       alert(document.getElementById("inp1").value + " " + document.getElementById("inp2").value);
   }

What confuses me is that on running the alert box says "on on" on clicking either of the buttons. Shouldn't it be "on off" or "off on"?

Upvotes: 1

Views: 95

Answers (4)

Paul S.
Paul S.

Reputation: 1573

Use checked instead, but keep in mind that it will give you a boolean value, so the following code will do what you need:

function show() {
   alert(document.getElementById("inp1").checked ? 'on' : 'off'
 + " " + document.getElementById("inp2").checked ? 'on' : 'off'
   );
}

Upvotes: 0

blfuentes
blfuentes

Reputation: 2827

You should use the checked property, the value only determines what's inside when checked.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<script type="text/javascript">
    function show() {
        alert(document.getElementById("inp1").checked + " " + document.getElementById("inp2").checked);
    }
</script>
</head>
<body>
<input type="radio" id="inp1" name="same" onclick="show();"/>
<input type="radio" id="inp2" name="same" onclick="show();"/>
</body>
</html>

Upvotes: 0

Quentin
Quentin

Reputation: 943214

No, it shouldn't. The value is whatever you specify in the value attribute (and defaults to 'on' for radio buttons if you fail to supply one).

Since only a checked radio button can be successful and sent to the server, changing the value is not needed (the data just won't be included when the form is submitted).

The checked status is stored in the checked property, and you can use that from JavaScript to determine which radio button is the currently checked one.

Upvotes: 3

Ivan Chernykh
Ivan Chernykh

Reputation: 42166

Seems like what you want to get is checked property , have a look:

   function show() {
       alert( document.getElementById("inp1").checked + " " + 
              document.getElementById("inp2").checked);
   }

Working example: http://jsfiddle.net/w7vGL/

Upvotes: 1

Related Questions