开发者

Can I use .submit as a function?

I would like to show a div when the enter key or submit(/button) is used. I tried:

$("#inputfield").submit( function () {
$("#div").sho开发者_开发知识库w();
});

It doesn't work and I don't understand why. I googled for this but I didn't find a proper solution. Help would be appreciated.


Input fields don't emit submit events. You need to wrap the input in a form and attach the submit event to that. Then it will work like you intend, as long as you remember to return false to prevent the form from actually submitting.


I'm sure all your input fields are wrapped inside of a form tag. Pressing enter, or submitting a form via the submit button doesnt trigger the submit event on the input that had focus when you pressed enter, or on the submit button, but rather on the form element. So you need to check for the submit event on your form element.

Also, showing a div on form submit wont be much help because the default action is to then redirect, so you need to prevent the default action by doing return false;. If you want to stay on the same page and show a div, yet at the same time still submit the form data, you cn do that via ajax using $.post

$("form").submit( function () {
    $("#div").show();
    $.post('some_url_to_submit_to.php',$(this).serialize(), function(data){
        //some action to take on success... but not necessary
    })
    return false; // to prevent the form from redirecting to a new page
});


According to the documentation for .submit:

The submit event is sent to an element when the user is attempting to submit a form.

So you want to include inputfield in a form and bind the function like this:

$("#myForm").submit( ...
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜