如何使用jquery或javascript获取单选按钮Id值

时间:2011-05-25 19:56:58

标签: javascript jquery asp.net-mvc

我认为我有这个代码。

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

在我的Controller post Action结果中,我试图获取我正在做的这个选择的值

collection["selection"]

我无法获得我检查过的单选按钮ID。我正在“开启”,但我如何知道在我的视图中选择了哪个单选按钮?

谢谢

4 个答案:

答案 0 :(得分:4)

此功能将为您提供所选的单选按钮值及其ID。

 $("input:radio[name=selection]").click(function() {
        var value = $(this).val();
        alert(value);
        var id= $(this).attr('id');
        alert(id);
    });

答案 1 :(得分:1)

为您的单选按钮添加“值”属性:

<input type="radio" id="Default Selections" name="selection" value="default" />    
<input type="radio" id="Existing Selections" name="selection" value="existing" />

然后您可以通过以下方式区分它们:

$("[name=selection]").each(function (i) {
    $(this).click(function () {
        var selection = $(this).val();
        if (selection == 'default') {
            // Do something
        }
        else {
            // Do something else
        }             
    });
});

答案 2 :(得分:1)

您可以忘记单选按钮中的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">
<% } %>

答案 3 :(得分:0)

 $("input:radio[name=selection]").click(function (){
    var somval = $(this).val();  
    alert(somval);
  });