views:

1153

answers:

1

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', behaviour is different

+3  A: 

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"&gt;&lt;/script&gt;

</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>
Marek Karbarz