Reputation: 5259
I have a simple form that triggers an ajax call but as soon as the submit button is clicked the form resets and clears all entries. Do you know how to prevent this? I'd like to have control over when the form gets cleared.The code is below. I suspect I need to abandon the submit function and detect the "click" event on a button.
JQuery
$("#Formid").submit(function(){loadAjax();});
HTML
<form id="Formid" method="put">
Name<BR/>
<input type="text" name="name"/><BR/><BR/>
Node Id<BR/>
<input type="text" name="node_id"/><BR/><BR/>
Type<BR/>
<input type="text" name="type"/><BR/><BR/>
Parent<BR/>
<input type="text" name="parent_id"/><BR/><BR/>
Longitude<BR/>
<input type="text" name="longitude"/><BR/><BR/>
Latitude<BR/>
<input type="text" name="latitude"/><BR/><BR/>
Description<BR/>
<textarea name="description" rows="5" cols="40">Insert description here</textarea><BR/><BR/>
<input type="submit" value="Add Node"/>
</form>
Upvotes: 5
Views: 28143
Reputation: 645
I have prevented form clearing for search form for my website mrnams.com
View
@using (@Html.BeginForm("Search", "Home", FormMethod.Post, new { @class = "navbar-form navbar-right pull-right" }))
{
<div class="input-group">
<input id="input-searchQuery" type="text" class="form-control" placeholder="Search this site" name="q">
<span class="input-group-btn">
<button type="submit" class="btn btn-default">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
}
jQuery functions in View
@section scripts{
<script type="text/javascript">
$(function () {
var queryReturned = '@ViewBag.SearchQuery';
$("#input-searchQuery").val(queryReturned);
});
</script>
}
And here is the controller.
public class Home : Controller
{
public ActionResult Search(string q)
{
ViewBag.SearchQuery = q;
}
}
For demo visit https://mrnams.com/
Upvotes: 0
Reputation: 30453
You can use e.preventDefault()
or return false;
within a jQuery event handler:
$("#Formid").submit(function (e) {
loadAjax();
e.preventDefault(); // or return false;
});
e.preventDefault() will prevent the default event from occuring, e.stopPropagation() will prevent the event from bubbling up and return false will do both.
Upvotes: 0
Reputation: 46
Alternatively, you could use event.returnValue = false;
$("#Formid").submit( function(e) {
loadAjax();
e.returnValue = false;
});
This works similarly to "return false;", except it will not exit the function.
Upvotes: 0
Reputation: 144679
You can use preventDefault
method of the event object.
$("#Formid").submit(function(event){
loadAjax();
event.preventDefault()
})
Upvotes: 10