2017-01-07 7 views
0

3つのラジオボタンの値を取得する必要があります。私は3つのフォームフィールドを持っています。jqueryラジオボタンで未定義エラーを解決する方法

$('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 } ?> 
+0

.listing_typeは2つの異なる要素を入力していますか? –

+0

'$ res [" name "]'は 'undefined'ですか? – Mottie

答えて

0

トリックを行う必要があります

$('.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>

0

input.listing_type:radio:checkedで試してみてください。ここでは、tagName input、className listing_type、jqueryのフォームセレクタ:radio、CSS3セレクタ:checkedなど、さまざまな種類のセレクタを使用しています。