I wish to execute a jquery based ajax form submission on pressing the enter key. Obviously this involves stopping the normal form submission process. My form consists of a single input field. Here is the code:
<script type="text/javascript">
$(document).ready(function() {
// add vid ajax
$.ajaxSetup({
cache:false;
});
var ajax_load = '<div class="displayBox">Adding url...</div>';
var loadUrl = 'ajax/add';
$("#vidForm").submit(function(){
e.preventDefault();
alert("hello");
/*$("body").html(ajax_load)
.load(loadUrl,{url:$("#addurl").value},function(responseText){
$("#videos").append(responseText);
});*/
return false;
});
});
</javascript>
...
<form id="vidForm" action="ajax/">
<input id="addurl" name="addurl"/>
</form>
I’d expect the above to submit to ‘ajax/add’ but it doesn’t, submitting instead a full blown http-request to ‘ajax’ the default behaviour (in Chrome at least).
What am I doing wrong?
Update: Now that you’ve cleared up the earlier issues, I’m not seeing any problem. Fundamentally, it works: http://jsbin.com/ugowa4 (Tested on Chrome, Firefox, and Opera for Linux; IE6 and IE8.) You’ll have to walk through with a debugger to figure out at what point things are failing. The basics should work.
Looks like you’ve forgotten to declare the event parameter:
Without it, you’re trying to access a variable
efrom the containing scope. If there isn’t one, or it doesn’t have a function calledpreventDefault, you’ll get an exception at that point and the rest of the function will be ignored.See also Nick’s note about the closing tag (should be
</script>) and the misplaced;.