Submit a form without submit button and without page refresh?

a 夏天 提交于 2019-12-22 09:39:25

问题


I have a form which I cannot change and I have to handle its submit function from jquery only.

The form have radio buttons only. I want to submit the form without the page refereshed when a radio button is checked.

Here is the code which i tried.

$('input[type="radio"]').click(function(){
    if ($(this).is(':checked'))
    {
      $('form#my-form').submit(function(){
        alert('form submitted');
      });
    }
});

It should alert the "form submitted" but it does not.

Any thing which I am doing wrong?


回答1:


If you want to submit the form without pageload, then you need to go for ajax.

If you want the alert while submitting, you need to modify ur code a bit..

$('input[type="radio"]').click(function(){
    if ($(this).is(':checked'))
    {
      $('form#my-form').submit();
    }
});

$('form#my-form').submit(function(){
        alert('form submitted');
      });



回答2:


I tried this example on jsFiddle. My code will submit the form on check of a radioButton.

$('input[type="radio"]').click(function(){
    if ($(this).is(":checked"))
      $('form#my-form').submit();
});​

If you'd like to alert anything on submit of your form you have to add this code

$("#my-form").submit(function() {
    alert("submitting form ...");        
});



回答3:


Your code works well - just make sure you put this code inside document.ready event.

$(document).ready(function() {
    $('input[type="radio"]').click(function(){
        if ($(this).is(':checked'))
        {
          $('form#my-form').submit(function(){
            alert('form submitted');
          });
        }
    });
})

Please note that this selector is looking for ALL radio buttons. Also if you don't need to refresh page - you should add return false; to submit function.

But remember that is your case you need to click on radio button first to make you submit function working.




回答4:


The code inside your IF says: "If the form is submited then alert user". So you have to submit the form manually when the radio control is checked.

Before closing the IF, enter the following code:

$('yourForm').submit();



回答5:


In this case you just listen for the submit event. If you want to trigger the submit event you have add this line:

$('form#my-form').submit();




回答6:


Because you want your page to not be refreshed, use Ajax, here is the official documentation:

http://api.jquery.com/jQuery.ajax/



来源:https://stackoverflow.com/questions/12386999/submit-a-form-without-submit-button-and-without-page-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!