jQuery仅获得第一个单选按钮值

时间:2018-07-27 12:37:10

标签: jquery radio-button radio-group

我到处搜索,仍然无法正常工作。 我有这个广播组:

var tipo = jQuery("input[name=tipo]:checked").val();

  teste.click(function(){
    console.log(tipo);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divLabel"><label for="tipo">Tipo:</label></div>
  <div class="divInput">
    <input type="radio" name="tipo" value="0" id="tipo_1" class="tipo" checked>
      Diárias
      <input type="radio" name="tipo" value="1" id="tipo_2" class="tipo">
      Indenização de Campo
</div>

但是当我更改单选按钮选项时,var tipo 无法获得当前值。它始终仅显示值 0

我想念什么?

2 个答案:

答案 0 :(得分:0)

以下代码

var tipo = jQuery("input[name=tipo]:checked").val();

...必须在您的事件函数中,否则它将仅在开始时处理一次,并且永远不会再处理,请尝试以下操作:

teste.click(function(event){
  let tipo = jQuery("input[name=tipo]:checked").val()
  alert(tipo)
});

答案 1 :(得分:0)

您可以按照

进行操作

$(document).ready(function(){
    $('input[type=radio][name=tipo]').change(function(){
        var value = $(this).val();
          alert(value);
    });
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
  <div class="divLabel"><label for="tipo">Tipo:</label></div>
    <div class="divInput">
       <input type="radio" name="tipo" value="0" id="tipo_1" class="tipo" checked>Diárias
      <input type="radio" name="tipo" value="1" id="tipo_2" class="tipo">Indenização de Campo
    </div>
</body>
</html>