如何解决 jQuery 中未定义的错误单选按钮



我需要获取三个单选按钮的值。我有 3 个表单字段。

$('input[name=optradio]:checked').val();提供了正确的答案。然而

$('.listing_type input:radio:checked').val();返回undefined .

我该如何解决这个问题?

var listing=$('input[name=optradio]:checked').val();
console.log(listing);
var overwrite = $('.listing_type input:radio:checked').val();
alert(overwrite);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<?php
$response = Array
(
    "0" => Array
        (
            "id" => "57fde39205dd7b0ef89e02e3",
            "name" => "SELL"
        ),
    "1" => Array
        (
            "id" => "57fde3aa05dd7b0ef89e02e4",
            "name" => "RENT"
        )
);
echo "<pre>";
print_r($response);
echo "</pre>";
$count = count($response);
foreach($response as $res)
{
$property = "RENT";
?>
<input type="radio" name="optradio"  class="listing_type" value="<?php echo $res["name"];?>" 
    <?php 
    if($property==$res["name"])
    { 
    echo "checked=checked";
    }
    ?>><?php 
    $l_t=$res["name"];
    if($l_t == "SELL"){
        echo "Sell";
    }else{
        echo "Rent";
    }
    ?>
<?php } ?>

尝试使用

$('.listing_type:input:radio:checked').val();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<body><pre>Array
(
    [0] =&gt; Array
        (
            [id] =&gt; 57fde39205dd7b0ef89e02e3
            [name] =&gt; SELL
        )
    [1] =&gt; Array
        (
            [id] =&gt; 57fde3aa05dd7b0ef89e02e4
            [name] =&gt; RENT
        )
)
</pre>
  <input type="radio" name="optradio" class="listing_type" value="SELL">Sell
  <input type="radio" name="optradio" class="listing_type" value="RENT" checked="checked">Rent
  <script>
    var listing = $('input[name=optradio]:checked').val();
    console.log(listing);
    var overwrite = $('.listing_type:input:radio:checked').val();
    alert(overwrite);
  </script>
</body>

input.listing_type:radio:checked应该可以解决问题。你在这里使用了很多种选择器:tagName input、className listing_type、jquery 的表单选择器 :radio 和 CSS3 选择器 :checked

最新更新