$(document)...">

Jquery: checked undefined button input attribute

I have the following and in the following 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 starts, the warning will have the value "value = undefined"

BUT, if I put javascript after the div (or body), the warning will return using "value = Yes"

Why doesn't jquery recognize a type radio at the top of the page? If I create type = 'hidden', jquery can read / recognize the value if at the top of the page. When type = 'radio', the behavior is different

+3
source share
2 answers

, , , , jquery .

"" . , javascript ,

<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>
+3

undefined.

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

isChecked 'undefined'

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

isChecked true false

+5

Source: https://habr.com/ru/post/1728389/


All Articles