0

I want to use the same function if the user submit the #postcode-form or click on #show-results link. How can I do it without duplicate the function?

HTML

<form id="postcode-form">
    <input id="postcode" type="text" name="postcode" />
    <input type="submit" value="search" />
</form>
<a id="show-results" href="#">Show the results</a>​

JAVASCRIPT

$("#show-results").click(function(e){
        e.preventDefault();
        codeAddress(postcode);
});​
0

4 Answers 4

1
$("#postcode-form").submit(function(){
    //your submit function, validation, etc.
});

$("#show-results").click(function(e){
    $("#postcode-form").submit();
});
Sign up to request clarification or add additional context in comments.

Comments

1

Make the link submit the form instead:

$('#show-results').click(function(e){
    e.preventDefault();
    $('#postcode-form').submit();
});

Comments

1

You need to add onsubmit event on form forcefully stops form to submit and on click on submit-results link you can forcefully submit form either by ajax or simple form submit method.

<form id="postcode-form" onsubmit="return false;">
    <input id="postcode" type="text" name="postcode" />
    <input type="submit" value="search" />
</form>
<a id="show-results" href="#">Show the results</a>​

and the js

$('#show-results').click(function(e){
        e.preventDefault();
        $('#postcode-form').submit();
    });

1 Comment

Yeah, you're right but I would rather not mix the markup with inline js code. Instead add an event.preventDefault() to the submit method's function body.
0

You can use

$('#show-results').submit();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.