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

时间:2017-01-07 03:19:55

标签: javascript 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 } ?>

2 个答案:

答案 0 :(得分:0)

尝试

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

&#13;
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

input.listing_type:radio:checked应该做到这一点。您在这里使用了多种选择器:tagName input,className listing_type,jquery的表单选择器:radio和CSS3选择器:checked