简体   繁体   中英

Javascript - Radio Button onChange

Here is my code:

<html>
<head>
    <script type="text/javascript">
        function Change(radio)
        {   
            if(radio.value)
            {
                setvalue = "Yes";
                radiovalue = radio.value;
                value = setvalue;
                ChangeValue(radiovalue,value)
            }
        }  

        function ChangeValue(radiovalue, value)
        {
            alert(radiovalue+"=>"+value);
        }
    </script>
</head> 

<body>
<?php
for($i = 1; $i <= 3; $i++)
{
?>
    <input type="radio" name="choice" value="<?php echo $i;?>" onchange="Change(this);" /><br />
<?php
}
?>
</body>
</html>

There are 3 radio buttons in the web page.
From the above code, when I click the first radio button, it will show alert message for the radio button that I choosen (ie 1 => Yes).
Yes means that I choose the radio button.
No means that I didn't choose the radio button.

Now my questions is if I choose the first radio button, it will show alert message for each radio button
(ie 1 => Yes, 2 => No, 3 => No).
How should I modify?

In your example, radio.value will be the string "1" , "2" , or "3" . All of these are truthy, so the if block will always run. You need to compare the actual value using a comparison opperator such as == in your if statement.

Example:

if(radio.value == "1")

I cut and pasted your example into a web app and it worked just the way you'd expect - both IE and chrome - so don't know why you're getting strange results. The if(radio.value) simply checks for the existence of a value (javascript thing) and is coded correctly. You might try onchange="return Change(this)" as some browsers may not like the open call.

Plese try this

<html>
<head>
<script type="text/javascript">
function Change(radio) {   
  for (var i = 1; i < 4; i++) {
    var ele = document.getElementById("choice_"+i);
    if(ele.checked) {
      setvalue = "Yes";
      radiovalue = ele.value;
      value = setvalue;
      ChangeValue(radiovalue,value)
    } else {
      setvalue = "No";
      radiovalue = ele.value;
      value = setvalue;
      ChangeValue(radiovalue,value)
   }
  }             
}  

function ChangeValue(radiovalue, value) {
  alert(radiovalue+"=>"+value);
}
</script>
</head> 
<body>
<?php
for($i = 1; $i <= 3; $i++) {
?>
 <input type="radio" name="choice" id="choice_<?php echo $i;?>" value="<?php echo $i;?>" onchange="Change(this);" /><br />
<?php
}
?>
</body>
</html>

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