Quick Reach
What is jQuery preventDefault() method?
The event.preventDefault() method is used to prevent the default action of the element. For example, in HTML forms, as Submit button is clicked, preventing it from submitting the data to the server.
Similarly, it can be used to prevent other elements default action like opening links etc..
Example of event.preventDefault() to prevent form submit
In this example, as you try to submit the form by pressing the “submit now” button without entering any text in the First name field, the form default behavior of submission is prevented:
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
<html>
<head>
<script src=“http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js”>
</script>
<script>
$(document).ready(function(){
$(“#submittest”).submit(function(event){
alert(“Submit event occured”);
if (document.getElementById(“FName”).value==”){
event.preventDefault();
alert(“”);
}
else{
alert(“Not empty”);
}
});
});
</script>
</head>
<body>
<form id=“submittest” action=“#”>
First name:
<input type=“text” id=“FName”><br>
Last name:
<input type=“text” id=“LName”><br>
<input type=“submit” value=“submit now”>
</form>
</body>
</html>
|
Leave A Comment?