Ajax在PHP中获取第一个单选按钮的值

时间:2013-11-22 02:22:26

标签: javascript php jquery ajax forms

我有两组不同的单选按钮。在此下,当触发第二组单选按钮时,我触发将值传递给另一个文件。但问题是,在传递值时,jquery会获取第二组中第一个单选按钮的值。无论你选择哪个按钮。

<script type = "text/javascript">
$(document).ready(function(){
  $("#sub_category_form_cat_1").click(function()
  {
        var main_cat=$("#main_cat:checked").val();
        var sub_cat_form1=$("input:radio[name='sub-category_form_cat_1']:checked").val();
        $.ajax
        ({
            data: {'cat':main_cat,'sub_cat':sub_cat_form1},
            url: "ajax_files/events-select.php",
            type: 'GET',                
            success: function(data) 
            {
                $("#displayedresults").html(data);
                $('#loading_spinner').hide();
                $('#loading_text').hide();
                $('#loading_row').hide();
                $('#displayedresults').show();
                //$('.button_export').show();
                //$("a.button_export").attr("href", string);
            }
        });
        return false;
  });
});

<tr><td>Category:</td><td>
    <input type="radio" name="category_form_cat_1" value="Adults" id="main_cat" />&nbsp;Adults &nbsp;
    <input type="radio" name="category_form_cat_1" value="Kids" id="main_cat" />&nbsp;Kids</td></tr>
<tr><td>Sub-Category:</td><td>
    <input type="radio" name="sub-category_form_cat_1" value="Dance" id="sub_category_form_cat_1"/>&nbsp;Dance&nbsp;
    <input type="radio" name="sub-category_form_cat_1" value="Fitness" id="sub_category_form_cat_1"/>&nbsp;Fitness
    <input type="radio" name="sub-category_form_cat_1" value="Workshop" id="sub_category_form_cat_1"/>&nbsp;Workshop&nbsp;
    <input type="radio" name="sub-category_form_cat_1" value="Events" id="sub_category_form_cat_1"/>&nbsp;Events</td></tr>

2 个答案:

答案 0 :(得分:1)

您不能拥有多个具有给定id的元素。这将始终返回带有id的第一个元素。您需要引用表单

中的元素
var main_cat = $("input[name='category_form_cat_1']:checked").val();

由于这不起作用,让我们尝试不同的东西

<tr><td>Category:</td><td id="maincat>
    <input type="radio" name="category_form_cat_1" value="Adults" />&nbsp;Adults &nbsp;
    <input type="radio" name="category_form_cat_1" value="Kids" />&nbsp;Kids</td></tr>
<tr><td>Sub-Category:</td><td id="subcat">
    <input type="radio" name="sub-category_form_cat_1" value="Dance" />&nbsp;Dance&nbsp;
    <input type="radio" name="sub-category_form_cat_1" value="Fitness" />&nbsp;Fitness
    <input type="radio" name="sub-category_form_cat_1" value="Workshop" />&nbsp;Workshop&nbsp;
    <input type="radio" name="sub-category_form_cat_1" value="Events" />&nbsp;Events
</td></tr>

对于你的JS

var main_cat = $("#maincat").children("input:checked").val();

答案 1 :(得分:0)

id实际上是单个和唯一标签,你真正想做的是给所有无线电类名“sub_category_form_cat_1”,然后使用$(“。sub_category_form_cat_1”)。click(function(){}) ;