I have the following html
<form action="" class="form-horizontal" id="submitForm">
<input class="required input-xxlarge" type="text" placeholder="Please enter a suitable title" name="title">
<br><br>
<div id='container' class="well">
<br>
<textarea class="span8 required" id='mytextarea' wrap='on'>
Please enter some value
</textarea>
<br>
<input class="btn btn-info" type="submit" id="submit-button" value="Submit">
</div>
</form>
When the user clicks submit, I want to send the textarea data as well as the text data to a url. I am also using the validation plugin, just to ensure client side verification.
And the following is my jQuery:
$(function() {
$("#submitForm").submit(function(){
if ($("#submitForm").validate()){
$.post("/create/post/",
{'data':$('#mytextarea').val()},
function(data){
console.log(data);
alert(data);
});
}
});
});
As of now it does not seem to work, what is wrong? How can I override the submit button, perform validation and then post the data to the server?
validate()is just the initialization method for the plugin, not the one supposed to be used to check if the form is valid. Your provided code always “validates” to true, becausevalidate()returns the validation object. The actual check to see whether the form is valid is whatvalid()is for.In addition, as Demao wrote, you need to stop the event propagation so the form is submitted with ajax. One way is by returning false at the end of the callback.
So your code should be something like:
Here is a demo: http://jsfiddle.net/hzcF7/
Another way to do this would be to let the plugin do the validation itself and just tell it what to do if the form is valid, using the
submitHandleroption when you initialize the validation object. Like this:Demo