开发者

jquery: radio button input checked attribute is undefined

I have the following and in this order:

<script type="text/javascript">
  $(document).ready(function(){
     var overwrite = $('#itemList input:radio:checked').val() 

     alert('value = '+ overwrite);
  });
</script>
<body>
  <form ..... >
    <div id="itemList">
    Overwrite?
    <input type="radio" value="Yes" class="overWrite" name="overWrite" >Yes
    <input type="radio" value="No" class="overWrite" name="overWrite" >No
    </div>
  </form>
</body>

when it runs, the alert will have 'value = undefined'

BUT, if I put the javascript after the div (or body), the alert comes back with 'value = Yes'

Why does jquery not recognize the type radio at beginning of page? If I create a type = 'hidden', jquery can read/recognize the value if at beginning of page. When type = 'radio', beha开发者_运维问答viour is different


I had similar problem with 'undefined'.

when I tested this

var isChecked = $('#itemList').attr('checked');

isChecked was 'undefined'

and for this

var isChecked = $('#itemList').prop('checked');

isChecked is true or false


Problem you're running into seems to be that there are simply no checked radio buttons on page load so your jquery returns a null object.

This will check "no" by default and returns the correct value. So your javascript is technically correct, you just need to check for null values

<head>
<title>jQuery Tester</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

</head>

<body>
    <div id="itemList">
    Overwrite?
    <input type="radio" value="Yes" class="overWrite" name="overWrite"  />Yes
    <input type="radio" value="No" class="overWrite" name="overWrite" checked="checked" />No 
    </div>


<script type="text/javascript">
  $(document).ready(function(){
     var overwrite = $('#itemList input:radio:checked').val();

     alert('value = ' + overwrite);
  });
</script>
</body>
</html>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜