[英]Jquery Radio Button Check Issue
I'm using Jquery to store the value of a checked set of radio buttons into a variable and it works fine, but the issue I'm having is when someone decides to skip the question (skip the set of radio buttons -ie don't select an option) the value that is returned in the variable is 'undefined'. 我正在使用Jquery将选中的单选按钮集的值存储到变量中,并且工作正常,但是我遇到的问题是当某人决定跳过该问题时(跳过单选按钮集-ie don' t选择一个选项)变量中返回的值是“ undefined”。 I would like to have the value returned as blank (no value) if someone decides to skip a set of radio buttons. 如果有人决定跳过一组单选按钮,我希望将值返回为空白(无值)。 Is there an easy method to do this in Jquery? 有没有一个简单的方法来做到这一点在jQuery中?
Jquery: jQuery:
`var raq1= $('input[type=radio][name=q1]:checked').val();`
HTML: HTML:
`<input type="radio" name="q1" id="qn1i5" value="5">
<input type="radio" name="q1" id="qn1i4" value="4">
<input type="radio" name="q1" id="qn1i3" value="3">
<input type="radio" name="q1" id="qn1i2" value="2">
<input type="radio" name="q1" id="qn1i1" value="1">`
What you want to do is check whether $('input[type=radio][name=q1]:checked').val()
exists. 您要做的是检查$('input[type=radio][name=q1]:checked').val()
存在。 If it exists, set that value to raq1
. 如果存在,则将该值设置为raq1
。 If it doesn't, you simply set raq1
to be an empty string. 如果不是,则只需将raq1
设置为空字符串。
This can be done with the following ternary : 这可以通过以下三元数来完成:
$('input[type=radio][name=q1]:checked').val() ? $('input[type=radio][name=q1]:checked').val() : ''
And can be seen in the following: 并且可以在下面看到:
document.getElementsByTagName('button')[0].addEventListener("click", function() { var raq1 = $('input[type=radio][name=q1]:checked').val() ? $('input[type=radio][name=q1]:checked').val() : ''; console.log(raq1); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="radio" name="q1" id="qn1i5" value="5"> <input type="radio" name="q1" id="qn1i4" value="4"> <input type="radio" name="q1" id="qn1i3" value="3"> <input type="radio" name="q1" id="qn1i2" value="2"> <input type="radio" name="q1" id="qn1i1" value="1"> <button>Get Values</button>
Hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.