Ahmad
Ahmad

Reputation: 2129

Submit a form without submit button and without page refresh?

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?

Upvotes: 5

Views: 9717

Answers (6)

Vytalyi
Vytalyi

Reputation: 1695

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.

Upvotes: 1

user1678541
user1678541

Reputation:

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

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

Upvotes: 0

Pilgerstorfer Franz
Pilgerstorfer Franz

Reputation: 8359

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 ...");        
});

Upvotes: 1

sathish
sathish

Reputation: 800

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');
      });

Upvotes: 8

hazelnut
hazelnut

Reputation: 157

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();

Upvotes: 0

user1678541
user1678541

Reputation:

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();

Upvotes: 0

Related Questions