使用jQuery确定根据订单发送的按钮

时间:2012-06-09 11:10:08

标签: php jquery forms post radio-button

问题:

根据订单确定发送的单选按钮,并使用PHP提交值。

HTML表1代码:

<table class="table table-bordered neutralize" id="itembuttons">
    <thead>
        <tr>
            <th><input type="radio" name="3" id="3" value="6"></th>
            <th><input type="radio" name="3" id="3" value="7"></th>
            <th><input type="radio" name="3" id="3" value="8"></th>
            <th><input type="radio" name="3" id="3" value="9"></th>
            <th><input type="radio" name="3" id="3" value="10"></th>
        </tr>
    </thead>
</table>

HTML表2代码:

<table class="table table-bordered neutralize" id="itembuttons">
    <thead>
        <tr>
            <th><input type="radio" name="3" id="3" value="11"></th>
            <th><input type="radio" name="3" id="3" value="12"></th>
            <th><input type="radio" name="3" id="3" value="13"></th>
        </tr>
    </thead>
</table>

情境:

上面的代码将在PHP中生成一个名为“3”的POST变量,表1中的值介于6和10之间,表2中的值介于11和13之间。但是,我希望jQuery确定实际选择了哪个按钮。因此,例如,如果我选择第3个按钮(值= 8或值= 13),那么值3应该在隐藏的输入字段中发送。如果选择了第5个按钮(值= 10),则应在隐藏的输入字段中发送值5.

3 个答案:

答案 0 :(得分:1)

试试这个 - http://jsfiddle.net/Xa42c/

$("input[type=radio]").on("click", function(e) {
    $("input[type=hidden]").val( $(this).val() );

    alert( "Hidden field value is set to " + $(this).val() );
});​

请注意,您不需要id - s。但是如果你想使用它们,必须是唯一的

更新要使用职位index() - http://jsfiddle.net/Xa42c/2/

$("input[type=radio]").on("click", function(e) {
    var index = $("input[type=radio]").index(this) + 1;
    $("input[type=hidden]").val( index );

    alert( "Hidden field value is set to " + index );
});​

答案 1 :(得分:0)

您的代码存在的问题是ID不是唯一的。尝试更改它们。如果您需要一些通用名称,可以使用表的name属性。

答案 2 :(得分:0)

最终解决方案:

$(document).ready(function() {
    $('input[type=radio]', $('#itembuttons')).click(
        function() {
            var pos = $(this).parent().index() + 1;
            $('#hdnQuestion').val(pos);
            alert( 'The ' + $('#hdnQuestion').attr('name') + ' value is now ' + $('#hdnQuestion').val() );
        }
    );
});