gpt4 book ai didi

javascript - $( "#id").val();显示错误结果?

转载 作者:行者123 更新时间:2023-11-28 11:52:56 24 4
gpt4 key购买 nike

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" 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>

如果我选择 Male 选项并运行 val() 我不会得到 Male:

$( "#gender" ).val();
"Female"

为什么我会成为女性?

最佳答案

因为两个单选按钮具有相同的 ID(顺便说一句,这在 HTML 中是无效的)。使用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>

关于javascript - $( "#id").val();显示错误结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32052439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com