Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 435
Larry Avatar asked Dec 22 '22 06:12

Larry


1 Answers

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

like image 173
Pažout Avatar answered Jan 05 '23 02:01

Pažout