$(“#id”)。val();显示错误的结果?

时间:2015-08-17 14:03:26

标签: javascript jquery html

HTML:

execution error: Microsoft Outlook got an error: Error while saving the changed record property. (-2700)

如果我选择男性选项并运行<div class="form-group btn-group btn-group-justified" data-toggle="buttons"> <label class="btn btn-default btn-lg"> <input type="radio" name="gender" value="Female" id="gender" required><i class="fa fa-female"></i> Female </label> <label class="btn btn-default btn-lg"> <input type="radio" name="gender" value="Male" id="gender" required><i class="fa fa-male"></i> Male </label> </div> 我不会得到男性:

val()

为什么我会成为女性?

3 个答案:

答案 0 :(得分:3)

因为两个单选按钮具有相同的ID(在HTML中btw无效)。改为使用attribute selector旁边的checked pseudo selector

alert($("input[name='gender']:checked").val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group btn-group btn-group-justified" data-toggle="buttons">
      <label class="btn btn-default btn-lg">
        <input type="radio" name="gender" value="Female" required><i class="fa fa-female"></i> Female
      </label>
      <label class="btn btn-default btn-lg">
        <input type="radio" name="gender" value="Male" required checked><i class="fa fa-male"></i> Male
      </label>
    </div>

答案 1 :(得分:3)

请使用:checked

&#13;
&#13;
$('input[name="gender"]').change(function(){
    alert($('input[name="gender"]:checked').val())
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="form-group btn-group btn-group-justified" data-toggle="buttons">
  <label class="btn btn-default btn-lg">
    <input type="radio" name="gender" value="Female" id="gender_female" required><i class="fa fa-female"></i> Female
  </label>
  <label class="btn btn-default btn-lg">
    <input type="radio" name="gender" value="Male" id="gender_male" required><i class="fa fa-male"></i> Male
  </label>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

你的HTML

<div class="form-group btn-group btn-group-justified" data-toggle="buttons">
  <label class="btn btn-default btn-lg">
    <input type="radio" name="gender" value="Female" required><i class="fa fa-female"></i> Female
  </label>
  <label class="btn btn-default btn-lg">
    <input type="radio" name="gender" value="Male"  required><i class="fa fa-male"></i> Male
  </label>
</div>

jquery的

$("input[name=gender]").click(function() {
      alert($(this).val());
});

Fiddle