1

I have an ajax form I would like to prevent from preforming an action when submitted and have tried numerous methods and nothing works. My first method was:

 return false;

and then I tried

event.preventDefault();

event being the callback name or whatever you call it.

function(event) {
    event.preventDefault();
};

Heres the HTML I am using right now:

<form class="main_search" method="POST" action="ajaxsearch.php">
    <input type="text" class="editable" placeholder="Search">
</form>

Heres the test javascript I set up:

$('.main_search').submit(function(event) {
    event.preventDefault(console.log(event)); //Log the event if captured
});

Neither method works but the weird part is that they work on different things like buttons but they don't work on this one form. Am I missing something here? Thanks!

4
  • 3
    This is weird: event.preventDefault(console.log(event)); Those should be two lines (event.preventDefault(); doesn't take any arguments). Commented Feb 19, 2012 at 2:28
  • @JaredFarrish That would be a good reason but it still doesn't work Commented Feb 19, 2012 at 2:29
  • 2
    I didn't say it was a reason, I said this is weird. Otherwise, I would have posted it as an answer. ;) Commented Feb 19, 2012 at 2:31
  • 1
    What's you've posted seems to work: jsfiddle.net/5TVGn Is this a dynamically added form? Commented Feb 19, 2012 at 2:32

2 Answers 2

2

To deal with your specific problem (ie, inserting dynamically generated form), use $.on(). You're better off not using document.body as the parent observer (as $.live() essentially does) with $.on(), so the following would be appropriate (considering your actual markup):

<div id="searches">
    <form class="main_search" method="POST" action="ajaxsearch.php">
        <input type="text" class="editable" placeholder="Search">
    </form>
</div>

var $main_search = $('.main_search'),
    $searches = $('#searches');

$searches.on('submit', '.main_search', function(event) {
    event.preventDefault();
    console.log(event); //Log the event if captured
});

setInterval(function(){
    $searches.append($main_search.clone());
}, 5000);

http://jsfiddle.net/5TVGn/2/

Sign up to request clarification or add additional context in comments.

Comments

1

I set up a JSfiddle:

http://jsfiddle.net/XM679/

Could it be you forgot to wrap it into $(document).ready(function() {} ? If this didn't solve the problem: Since the fiddle is working - we would need your context to help more.

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.