读取单选按钮的值时,值未定义

时间:2019-04-17 09:10:26

标签: javascript jquery html

我正在尝试获取所选单选按钮的值。我尝试了以下方法,但获得的值为undefined

var nameSelected;
$('.m-radio-inline input').on("change", function() {
  nameSelected = $('input[name="abc"]:checked').val();
});
alert(nameSelected);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="m-radio-inline">
  <label class="m-radio">
    <input type="radio" name="abc"  value="Ash" checked> 
    Ash
    <span></span>
  </label>
  <label class="m-radio">
    <input type="radio" name="abc"  value="Win"> 
    Win
    <span></span>
  </label>
</div>

应该给灰烬/胜利

3 个答案:

答案 0 :(得分:3)

因为它在nameSelected出现值之前发出警报-将alert放在change处理程序内:

var nameSelected;
$('.m-radio-inline input').on("change", function() {
  nameSelected = $('input[name="abc"]:checked').val();
  alert(nameSelected);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="m-radio-inline">
  <label class="m-radio">
	<input type="radio" name="abc"  value="Ash" checked>Ash
	<span></span>
  </label>
  <label class="m-radio">
       <input type="radio" name="abc"  value="Win">Win
       <span></span>
  </label>
</div>

答案 1 :(得分:0)

alert(nameSelected);在执行此行时未触发事件。

答案 2 :(得分:0)

您必须对某些操作名称发出警报,第一次选择的是未定义的,并且更改功能上设置了值,因此它会警报未定义的

<!-- begin snippet: js hide: false console: true babel: false -->



var nameSelected;
$('.m-radio-inline input').on("change", function() {
  nameSelected = $('input[name="abc"]:checked').val();
  alert(nameSelected);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="m-radio-inline">
  <label class="m-radio">
		<input type="radio" name="abc"  value="Ash" checked>Ash<span></span>
	</label>
  <label class="m-radio">
    <input type="radio" name="abc"  value="Win">Win<span></span>
	</label>
</div>