Submitting a jQuery ajax form with two submit butt

2019-01-13 21:27发布

I have a form that looks like this:

<form action="/vote/" method="post" class="vote_form">
    <input type="hidden" name="question_id" value="10" />
    <input type="image" src="vote_down.png" class="vote_down" name="submit" value="down" />
    <input type="image" src="vote_up.png" class="vote_up" name="submit" value="up" />
</form>

When I bind to the form's submit ($("vote_form").submit()), I don't seem to have access to which image the user clicked on. So I'm trying to bind to clicking on the image itself ($(".vote_down, .vote_up").click()), which always submits the form, regardless of whether I try

  • return false;
  • event.stopPropogation(); or
  • event.preventDefault();

because all of those are form events.

  1. Should I attach my $.post() to the form.submit() event, and if so, how do I tell which input the user clicked on, or

  2. Should I attach my $.post() to the image click, and if so, how do I prevent the form from submitting also.

Here is what my jQuery code looks like now:

$(".vote_up, .vote_down").click(function (event) {
    $form = $(this).parent("form");
    $.post($form.attr("action"), $form.find("input").serialize() + {
        'submit': $(this).attr("value")
    }, function (data) {
        // do something with data
    });
    return false; // <--- This doesn't prevent form from submitting; what does!?
});

8条回答
Juvenile、少年°
2楼-- · 2019-01-13 22:03

You can also try out the jquery From Plugin which as all sorts of nice tools for submitting forms via ajax.

http://malsup.com/jquery/form/

查看更多
\"骚年 ilove
3楼-- · 2019-01-13 22:16

Try adding onsubmit="return false;" to your form, and then submitting your form with javascript:

<form action="/vote/" method="post" name="vote_form" class="vote_form" onsubmit="return false;">
    <input type="hidden" name="question_id" value="10" />
    <input type="image" src="vote_down.png" class="vote_down" name="submit" value="down" onclick="imageClicked(this)"/>
    <input type="image" src="vote_up.png" class="vote_up" name="submit" value="up" onclick="imageClicked(this)"/>
</form>

<script>
function imageClicked(img) {
    alert(img.className);
    document.forms["vote_form"].submit();
}
</script>
查看更多
登录 后发表回答