Visit Mozilla.org

DOM:event.preventDefault

z Mozilla Developer Center, polskiego centrum programistów Mozilli.

« Dokumentacja Gecko DOM

UWAGA: Tłumaczenie tej strony nie zostało zakończone.
Może być ona niekompletna lub wymagać korekty.
Chcesz pomóc? | Dokończ tłumaczenie | Sprawdź ortografię | Więcej takich stron...

Spis treści

[edytuj] Podsumowanie

Anuluje zdarzenie (jeśli można je anulować).

[edytuj] Składnia

event.preventDefault() 

[edytuj] Przykład

Toggling a checkbox is the default action of clicking on a checkbox. This example demonstrates how to prevent that happening:

<html>
<head>
<title>przykład preventDefault</title>

<script type="text/javascript">

function stopDefAction(evt) {
  evt.preventDefault();
}
</script>
</head>

<body>

<p>Please click on the checkbox control.</p>

<form>
<input type="checkbox" onclick="stopDefAction(event);"/>
<label for="checkbox">Checkbox</label>
</form>

</body>
</html>

Zobacz preventDefault podczas działania tutaj.

The following example demonstrates how invalid text input can be stopped from reaching the input field with preventDefault().

<html>
<head>
<title>przykład preventDefault</title>

<script type="text/javascript">

function checkName(evt) {
var charCode = evt.charCode;

  if (charCode != 0) {
    if (charCode < 97 || charCode > 122) {
      evt.preventDefault();
      alert("Please use lowecase letters only." + "\n"
            + "charCode: " + charCode + "\n"
      );
    }
  }
}

</script>
</head>

<body>

<p>Proszę wpisać swoje imię korzystając tylko z małych liter.</p>
<form>
<input type="text" onkeypress="checkName(event);"/>
</form>

</body>
</html>

[edytuj] Uwagi

W tym wypadku domyślny odnosi się do domyślnej akcji wykonywanej, gdy zdarzenie jest obsługiwane. Wywołanie preventDefault anuluje tę akcję.

Calling preventDefault during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.

You can use event.cancelable to check if the event is cancelable. Calling preventDefault for a non-cancelable event has no effect.

preventDefault doesn't stop further propagation of the event through the DOM. event.stopPropagation should be used for that.

[edytuj] Specyfikacja

DOM Level 2 Events: preventDefault