Arav
Arav

Reputation: 5247

jquery submit doesn't submit the form

I don't want to use input type="image" or input type="submit". Was trying to use img html tag as submit button when it's clicked. The click event on img tag and submit event on form works but the form is not getting submitted. Have the below HTML code

<form id="srch_id_form" name="srch_form" method="post" action="http://phbtxt.com.au:8080/cgi-bin/testpost.cgi" > 
    <img id="srch_id_submitform" src="update.png" />
</form>

Pasted the jquery code below. I get the alert box "form is submitting" when the image is clicked but the form is not getting submitted.

$("#srch_id_submitform").click(function(){
    $("#srch_id_form").submit();
});

$("#srch_id_form").submit(function(){
    alert('Form is submitting');
    return true;
});

Upvotes: 0

Views: 207

Answers (1)

JotaBe
JotaBe

Reputation: 39004

Difference between jQuery selector and DOM element: a jQuery selector is a wrapper for a collection of DOM elements. If you call a function on a jquery selector, the called function is a jQuery function. If you need to call a function on a DOM element, you have to access the DOM element which is inside the jQuery collection, and call the function from it. To do this you use get(index), where index is the index of the element inside the jQuery collection. If your jQuery selector only has one element, .get(0) is the DOM element.

submit() is 2 very different things:

  • in jQuery, it's an event, which is normally triggered when a form is submitted (i.e. normally, when a form is submitted, this event is triggered, and you can do something if you have defined a handler for it). If you call .submit() in jQuery, it will trigger all the handlers for this event... but it won't submit the form.
  • in a DOM element, it only exists for form elements, and is a method that submits the form

You don't have to trigger the submit() event, but to call the submit() method of the form DOM element.

To do so, don't use the jQuery selector, but the DOM form element itself:

$("#srch_id_form").get(0).submit();

get() returns the DOM element from a jQuery selector.

Note: when you use an element as an img to trigger an action it's very advisable to give visual clues to the user. You can do this using css cursor style, and change the style somewhat in the :hover state (pseudo-class) properties.

Upvotes: 3

Related Questions