如何使用 jquery 或 javascript 获取单选按钮 Id 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6130116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the radio button Id value using jquery or javascript
提问by user300485
I have this code in my view.
我有这个代码。
<%using (Html.BeginForm("X", "Y", FormMethod.Post, new { @id = "XSS" }))
{ %>
<fieldset>
<legend>Select Selection Type</legend>
<label>Default Selections:</label>
<input type="radio" id="Default Selections" name="selection" />
<br />
<label>Existing Selections:</label>
<input type="radio" id="Existing Selections" name="selection" />
</fieldset>
<input type="submit" value="submit">
<% } %>
In my Controller post Action result I am trying to get the value of this selection i am doing
在我的控制器发布操作结果中,我试图获得我正在做的这个选择的值
collection["selection"]
I am not able to get the radio button Id which I checked. I am getting "on" but How do I need to know which radio button was selected in my view?
我无法获得我检查过的单选按钮 ID。我正在“打开”但我如何需要知道在我的视图中选择了哪个单选按钮?
Thanks
谢谢
回答by Azam Alvi
This function will give you the selected radio button value and it's Id.
此函数将为您提供选定的单选按钮值及其 Id。
$("input:radio[name=selection]").click(function() {
var value = $(this).val();
alert(value);
var id= $(this).attr('id');
alert(id);
});
回答by Chris Wallis
Give your radio buttons the 'value' attribute:
给你的单选按钮 'value' 属性:
<input type="radio" id="Default Selections" name="selection" value="default" />
<input type="radio" id="Existing Selections" name="selection" value="existing" />
You can then distinguish between them with:
然后,您可以通过以下方式区分它们:
$("[name=selection]").each(function (i) {
$(this).click(function () {
var selection = $(this).val();
if (selection == 'default') {
// Do something
}
else {
// Do something else
}
});
});
回答by k-dev
You can forget about the id an put value attribute in your radiobuttons, code will look like this.
您可以忘记单选按钮中的 id 和 put 值属性,代码将如下所示。
<%using (Html.BeginForm("X", "Y", FormMethod.Post, new { @id = "XSS" }))
{ %>
<fieldset>
<legend>Select Selection Type</legend>
<label>Default Selections:</label>
<input type="radio" value="Default Selections" name="selection" />
<br />
<label>Existing Selections:</label>
<input type="radio" value="Existing Selections" name="selection" />
</fieldset>
<input type="submit" value="submit">
<% } %>
回答by Someone
$("input:radio[name=selection]").click(function (){
var somval = $(this).val();
alert(somval);
});