Navitas
Navitas

Reputation: 11

Checking form fields

I have a problem with checking form fields. I created some form and now I want to check the form fields. I wrote some html code but it doesn't really work and I don't know why. Here's the code:

<html>
<fieldset>
<legend>Formular</legend>
<head><title>Formular</title>
</head>
<body>
<script type="text/javascript">

    function checkform(){

    var strFehler='';

    if (document.forms[0].Betreff.value==""){

      strFehler += "Feld ist leern";}

    if (document.forms[0].Nachricht.value==""){

      strFehler += "Feld ist nicht ausgefülltn";}

    if (strFehler.length>0) {

      alert("Festgestellte Probleme: nn"+strFehler);

      return(false);
    }}
    </script>
    <form>
    <label for="text">Betreff</label>
    <input type="text">
    </label> <br>
    <label for="textarea">Nachricht</label>
    <textarea cols="50" rows="10">
    </textarea> <br>
    <button type="button" onclick="checkform">Senden</button>
    </form>
    </body>
    </fieldset>
    </html>

Upvotes: 0

Views: 53

Answers (2)

nalm
nalm

Reputation: 410

you need to use () when calling checkform

like this

<button type="button" onclick="checkform()">Senden</button>

and write your code in english pls, its easier to understand the context and help you

Upvotes: 1

CodeF0x
CodeF0x

Reputation: 2682

Several points here:

  • You didn't call checkform() properly. It has to be done like this: onclick="checkform()"
  • document.forms[0].Betreff.value=="" and document.forms[0].Nachricht.value=="" will produce a syntax error. To properly get the values, assign an id to your inputs, or get them by tag name as I did

function checkform() {

  var strFehler = '';

  if (document.getElementsByTagName('input')[0].value == "") {

    strFehler += "Feld ist leern";
  }

  if (document.getElementsByTagName('textarea')[0].value == "") {

    strFehler += "Feld ist nicht ausgefülltn";
  }

  if (strFehler.length > 0) {

    alert("Festgestellte Probleme: nn" + strFehler);

    return (false);
  }
}
<form>
  <label for="text">Betreff</label>
  <input type="text">
  <br>
  <label for="textarea">Nachricht</label>
  <textarea cols="50" rows="10"></textarea> <br>
  <button type="button" onclick="checkform()">Senden</button>
</form>

Upvotes: 1

Related Questions