传递变量jquery .submit

时间:2013-11-08 00:54:43

标签: php jquery forms submit selector

基本上我是通过jquery提交表单的。有多个具有多个ID的表单使用格式question_vote_ [some_value]。

我正在使用以下选择器接收提交内容:

$("form[id^='question_vote_']").submit(function(event){
    vote_on_question_recent(/* I need to add the value preceeding the id in here */);
    event.preventDefault();
})

这是我的表单代码:

<?php 
if ($question_choices)
{
    echo '<form action="" method="post" enctype="multipart/form-data" value="' . $question_details['question_id'] . '" id="question_vote_' . $question_details['question_id'] .  '">';
      while($question_choice = $database->fetch_array($question_choices)) 
      {
        // do something with the $row
        echo '<input type = "radio" name = "radio_button_recent_' . $question_details['question_id'] . '" id = "radio_button_' . $question_details['question_id'] .  '_' . $question_choice['choice_id'] . '" value = "' . $question_choice['choice_id'] . '" /> <label for = "' . $question_choice['choice_text'] . '">' . $question_choice['choice_text'] . '</label><br>';
      }
    echo '<input type="submit" name="voteOnQuestion" value="Vote!" class="login_home_sub"></form>';
}
?>

然后,我的'vote_on_question_recent'函数有以下代码:

function vote_on_question_recent(question_id)
{   
    var form_name = 'vote_form';
    var choice_id = $('[name=radio_button_recent_' + question_id + ' ]:checked').val();

    if(choice_id)
    {
        $.ajax({
            type:"POST",
            url: "API/index.php",
            data: {vote_form: form_name, question_id: question_id, choice_id: choice_id},
            success: function(result){
                if(result == 'success'){
                    alert(result);
                    return false;
                }
                else
                {
                    alert('error');
                    return false;
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr + ' / ' +  ajaxOptions + ' / Error:' + thrownError + ' Submitted choice:' + choice_id + ' question id:' + question_id);
                return false;
            }
        });

    }
}

所以基本上我正在寻找一些方法将'question_id'传递给我的javascript提交函数,或者获取提交表单的实际ID,这样我就可以解析它并获得ID。

1 个答案:

答案 0 :(得分:0)

您可以添加data-*属性来保存问题ID,并在提交处理程序中使用它来获取问题ID。

echo '<form action="" method="post" enctype="multipart/form-data" value="' . $question_details['question_id'] . '" id="question_vote_' . $question_details['question_id'] .  '" data-question="' . $question_details['question_id'] .  '">';

然后

$("form[id^='question_vote_']").submit(function(event){
    vote_on_question_recent($(this).data('question'));
    event.preventDefault();
})