繁体   English   中英

如何获取jQuery中最后选择的单选按钮ID?

[英]How to get the last selected radio button id in jQuery?

我想获取最后选择的单选按钮值的ID,以传递给数据库。 单选按钮正常工作。 但是无法获取最后选择的单选按钮的ID。

这是我的HTML代码。

$jsqla = mysql_query("select * from products where id='$product_id'") or die(mysql_error());
$jfeta = mysql_fetch_assoc($jsqla);

$formats = explode(";", $jfeta['formats']);

<div class="">
    <?php foreach($formats as $v){ ?>
        <label style="line-height: 1.25em;display: block;width: 100px;margin-right: 10px;float: left;">                         
            <div id="format-id_<?php echo $v?>" style="border: 1px solid;border-radius: 9px;text-align: center;padding-top: 10px;padding-bottom:10px;padding-left: 3px;padding-right: 3px;border-color: #cccccc;font-family: 'SSemibold'; font-size: 13px; color: #44b7da;">                                
                <input type="radio" value="<?php echo $v; ?>" name="abc" style="visibility:hidden;" id="<?php echo $v ?>" onClick="changeColour(this)"/>
                <span style="margin:-17px auto auto 0px;display:block;"><?php echo $v; ?></span>                            
            </div>                      
        </label>
    <?php } ?>      
</div>

这是我的jQuery代码。

$(document).ready(function(e) {
    var $radios = $(':radio'); 
    $divs = $radios.parent(); 
    var cvbl = "";

    $radios.bind('change', function() {
      var $this = $(this),
      $div = $this.parent();
      $div.css('background-color', this.checked ? '#cccccc' : '#ffffff');
      $divs.not($div).css('background-color', '#ffffff');

      var value = $(this).val();
      cvbl = value;
      alert(cvbl);
      alert($('.someClass:last') );
    });

 });

将脚本替换为以下脚本

$(document).ready(function(e) {
    var $radios = $(':radio');
    $divs = $radios.parent();
    var cvbl = "",
        radioId = "";

    $radios.bind('change', function() {
        var $this = $(this),
            $div = $this.parent();
        $div.css('background-color', this.checked ? '#cccccc' : '#ffffff');
        $divs.not($div).css('background-color', '#ffffff');

        var value = $(this).val();
        cvbl = value;
        radioId = $(this).attr('id');
        alert(radioId);
        alert(cvbl);
        alert($('.someClass:last'));
    });

});

在任何需要的地方使用变量radioId ,它将始终为您提供最后选择的单选按钮的ID。

您可以尝试以下代码:

if ($('input[name$="your radio button name"]:last').is(':checked')) {
    alert('the last radio');
    return false;

}

如果您没有单选按钮名称,请尝试以下操作

 if ($('input[type="radio"]:last').is(':checked')) {
    alert('the last radio');
    return false;

}

这对我有用...

$(".clsRadio").on("mousedown", function () {                  
var LastSelectedRadioButton = $('input[type=radio]:checked').attr('id');    
});

clsRadio是我的单选按钮组的一类。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM