开发者

JQuery if statements?

New to JQuery and was wondering how can I put the following JQuery code in an if statement so that it only runs when the submit button is clicked and does nothing when not clicked I know I'm using the $(".save-button").click(function() is there a way 开发者_如何学Pythonto put it in an if statement?

JQuery code.

$(function() {
    $(".save-button").click(function() {
        $.post($("#contact-form").attr("action"), $("#contact-form").serialize(), function(html) {
            $("div.contact-info-form").html(html);
            $('#changes-saved').append('<li>Changes saved!</li>').show().pause(1000).hide();
        });
        return false; // prevent normal submit
    });
});


calling .click and passing a function says "call this function when the element is clicked"

.click() without a function argument calls the click event

Therefore, there is no need for an 'if'


Well, you can check the type attribute of the clicked element e.g.:

//...
if ($(this).attr('type') == 'submit')
//...

But I would recommend you to use thesubmit event, remember that the form can be also submitted if the user presses Enter:

$(function() {
    $("#contact-form").submit(function() {
        var $form = $(this);
        $.post($form.attr("action"), $form.serialize(), function(html) {
            $("div.contact-info-form").html(html);
            $('#changes-saved').append('<li>Changes saved!</li>').show()
                               .pause(1000).hide();
        });
        return false; // prevent normal submit
    });
});


$(".save-button").click(function() {
    $.post($("#contact-form").attr("action"), $("#contact-form").serialize(), function(html) {
        $("div.contact-info-form").html(html);
        $('#changes-saved').append('<li>Changes saved!</li>').show().pause(1000).hide();
    });
    return false; // prevent normal submit
});

This will bind the click event to any element with .save-button class.


You can apply it only to submit buttons:

$(".save-button:submit")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜