简体   繁体   English

保存状态单选按钮javascript-html

[英]Save state radio button javascript-html

I´m trying to do a program that save the state of the radio button and check it. 我正在尝试一个保存单选按钮状态并检查它的程序。 This is my code but I don´t know what it`s wrong. 这是我的代码,但我不知道它的错误。 Help me please 请帮帮我

<script>
function saveState(){
   var ans1 = document.getElementById('grupo1');
   if (ans1.value == 1)
   {
       ans1.setAttribute("checked","checked");
       ans1.checked = true;
   }
</script>

<input type="radio" name="group" id="grupo1" value="1"> One
<input type="radio" name="group" id="grupo2" value="0"> Two
<input type="submit" onclick="saveState()" value="update">

Try this: 尝试这个:

<script>
    function saveState(){
        var ans1 = document.querySelector('input[name="group"]:checked').value;

        if (ans1.value == 1){
              ans1.setAttribute("checked","checked");
              ans1.checked = true;
        }
   }
  </script>

You perhaps mean this? 你或许这意味着什么?

You code does not make much sense unless the grupo1 button can change value 除非grupo1按钮可以更改值,否则您的代码没有多大意义

The following script assumes you have a standard cookie script somewhere 以下脚本假定您在某处具有标准cookie脚本

<script>
window.onload=function() {
  if (getCookie("grupo1")=="true") {
   document.getElementById('grupo1').click(); 
  }
  // either this
  document.getElementById('grupo1').onclick=function() {
     setCookie("grupo1","true")
  }
  // or this - depending on when you want to save the state
  document.getElementById("form1").onsubmit=function() {
    setCookie("grupo1",document.getElementById('grupo1').checked?"true":"false");
  }
}
</script>
<form id="form1">
<input type="radio" name="group" id="grupo1" value="1"> One
<input type="radio" name="group" id="grupo2" value="0"> Two
<input type="submit" value="update">
</form>

Being consequent in your approach towards placing brackets helps preventing situations like thisone. 在你的方法中放置括号有助于防止像这样的情况。

For example, if you place the opening bracket to functions, loops, conditional (if) statements etc on the same line as the condition itself (like you do above at the declaration of the function), you'll only have to look for the closing ones. 例如,如果将开括号放在与条件本身相同的行上的函数,循环,条件(if)语句等(就像你在函数声明中所做的那样),你只需要查找关闭的。

On the other hand, if you place both opening and closing brackets on their own line your code will be much more vertically symmetrical, which makes it easier to spot missing brackets if you're dealing with larger chunks of code. 另一方面,如果将开始和结束括号放在它们自己的行上,则代码将更加垂直对称,这使得在处理更大的代码块时更容易发现缺少的括号。

You should check out this article that deals with this particular issue: http://encosia.com/in-javascript-curly-brace-placement-matters-an-example/ 您应该查看这篇涉及此特定问题的文章: http//encosia.com/in-javascript-curly-brace-placement-matters-an-example/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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