Форма Отправить Пусто - PullRequest
       2

Форма Отправить Пусто

0 голосов
/ 05 ноября 2018

У меня есть форма, в которой я пытаюсь получить сообщение об ошибке, когда 3 поля пустые, когда я нажимаю кнопку Отправить, но это не работает, что я делаю не так? Я положил onsubmit в моей форме, но все еще не работает

HTML:

var message = document.getElementById("ErrorMessage");
    
function clearMyField(el) {
  if(el.placeholder !='') {
    el.placeholder = '';
  }
}
    

function checkforblank() {
  var allInputs = document.querySelectorAll('input[type=text]');
  for(let i = 0; i<allInputs.length; i++){
    let v = allInputs[i].value.trim();
    let n = allInputs[i].name;
    if(v == ""){
      message.textContent = n + " is empty";
      return false;
    }
  }
}
<!doctype html>
<html lang="en">
<head>
  <title> Lab 6 - Task 2 </title>
  <style>
  span {
padding-left: 10px;
display: block;
float: left;
width: 20%;
}
button { margin-left: 10px; }
body {
width: 80%; margin: auto; font-family: sans-serif;
border: 1px solid black;
}
  </style>
  <meta charset="utf-8">
  <script src="prototype.js"></script>
  <script src="task2.js"></script>
</head>
<body>
  <form id="myForm" method="get" onsubmit="return checkforblank()">
    <h1> Form Submit </h1>
    <p> <span>Name:</span> <input type="text" id="input1" placeholder="Enter Name" name="Name" onfocus="clearMyField(this);"></p>
    <p> <span>Student Id:</span> <input type="text" id="input2" placeholder="Enter Student ID" name="StudentID" onfocus="clearMyField(this);"></p>
    <p> <span>Email:</span> <input type="text" id="input3" placeholder="Enter Email" name="Email" onfocus="clearMyField(this);"></p>
    <p>
    <button id="submitButton" type="submit"> Submit </button>
    <input type="reset" value="Reset">
    </p>
    <p style="color:red" id="ErrorMessage"> &nbsp;</p>
  </form>

</body>
</html>

     
   

     
    
    

Ответы [ 4 ]

0 голосов
/ 06 ноября 2018

Вы не можете видеть сообщения об ошибках, потому что отправка формы обновляет страницу. Чтобы увидеть ошибки, используйте event.preventDefault , чтобы получить ошибки. Попробуйте следующий код.

        <html lang="en">

        <head>
            <title> Lab 6 - Task 2 </title>
            <style>
                span {
                    padding-left: 10px;
                    display: block;
                    float: left;
                    width: 20%;
                }
                button { margin-left: 10px; }
                body {
                    width: 80%; margin: auto; font-family: sans-serif;
                    border: 1px solid black;
                }
            </style>
            <meta charset="utf-8">
        </head>

        <body>
            <form id="myForm" method="get">
                <h1> Form Submit </h1>
                <p> <span>Name:</span> <input type="text" id="input1" placeholder="Enter Name" name="Name" onfocus="clearMyField(this);"></p>
                <p> <span>Student Id:</span> <input type="text" id="input2" placeholder="Enter Student ID" name="StudentID" onfocus="clearMyField(this);"></p>
                <p> <span>Email:</span> <input type="text" id="input3" placeholder="Enter Email" name="Email" onfocus="clearMyField(this);"></p>
                <p>
                    <button id="submitButton" type="submit"> Submit </button>
                    <input type="reset" value="Reset">
                </p>
                <p style="color:red" id="ErrorMessage"> &nbsp;</p>
            </form>

            <script>
                var message = document.getElementById("ErrorMessage");
                //document.getElementById('myForm')

                function clearMyField(el) {
                    if (el.placeholder != '') {
                        el.placeholder = '';
                    }
                }

                //Add event listener
                document.getElementById('myForm')
                    .addEventListener('submit', function (e) {
                        console.log('submit')
                        //prevent the default submission to see the errors.
                        e.preventDefault()
                        var allInputs = document.querySelectorAll('input[type=text]');
                        for (let i = 0; i < allInputs.length; i++) {
                            let v = allInputs[i].value.trim();
                            let n = allInputs[i].name;
                            if (v == "") {
                                message.textContent = n + " is empty";
                                return false;
                            }
                        }
                    })
            </script>
        </body>

        </html>
0 голосов
/ 05 ноября 2018

Тип кнопки должен быть submit вместо button. Поскольку вы сравниваете значение внутри функции, вы должны установить свойство placeholder для ввода вместо value

<button id="submitButton" type="submit"> Submit </button>

var message = document.getElementById("ErrorMessage");

function clearMyField(el) {
  if(el.placeholder !='') {
    el.placeholder = '';
  }
}


function checkforblank() {
  var allInputs = document.querySelectorAll('input[type=text]');
  for(let i = 0; i<allInputs.length; i++){
    let v = allInputs[i].value.trim();
    let n = allInputs[i].name;
    if(v == ""){
      message.textContent = n + " is empty";
      return false;
    }
  }
}
span {
  padding-left: 10px;
  display: block;
  float: left;
  width: 20%;
}
button { margin-left: 10px; }
body {
  width: 80%; margin: auto; font-family: sans-serif;
  border: 1px solid black;
}
<form id="myForm" method="get" onsubmit="return checkforblank()">
  <h1> Form Submit </h1>
  <p> <span>Name:</span> <input type="text" id="input1" placeholder="Enter Name" name="Name" onfocus="clearMyField(this);"></p>
  <p> <span>Student Id:</span> <input type="text" id="input2" placeholder="Enter Student ID" name="StudentID" onfocus="clearMyField(this);"></p>
  <p> <span>Email:</span> <input type="text" id="input3" placeholder="Enter Email" name="Email" onfocus="clearMyField(this);"></p>
  <p>
  <button id="submitButton" type="submit"> Submit </button>
  <input type="reset" value="Reset">
  </p>
  <p style="color:red" id="ErrorMessage"> &nbsp;</p>
</form>

Хотя я предпочту следующее:

var message = document.getElementById("ErrorMessage");

function clearMyField(el) {
  if(el.placeholder !='') {
    el.placeholder = '';
  }
}


function checkforblank() {
  var allInputs = document.querySelectorAll('input[type=text]');
  for(let i = 0; i<allInputs.length; i++){
    let v = allInputs[i].value.trim();
    let n = allInputs[i].name;
    if(v == ""){
      return false;
    }
  }
}
span {
  padding-left: 10px;
  display: block;
  float: left;
  width: 20%;
}
button { margin-left: 10px; }
body {
  width: 80%; margin: auto; font-family: sans-serif;
  border: 1px solid black;
}
<form id="myForm" method="get" onsubmit="return checkforblank()">
  <h1> Form Submit </h1>
  <p> <span>Name:</span> <input type="text" id="input1" placeholder="Enter Name" name="Name" onfocus="clearMyField(this);" required></p>
  <p> <span>Student Id:</span> <input type="text" id="input2" placeholder="Enter Student ID" name="StudentID" onfocus="clearMyField(this);" required></p>
  <p> <span>Email:</span> <input type="text" id="input3" placeholder="Enter Email" name="Email" onfocus="clearMyField(this);" required></p>
  <p>
  <button id="submitButton" type="submit"> Submit </button>
  <input type="reset" value="Reset">
  </p>
</form>
0 голосов
/ 05 ноября 2018

Вы можете использовать атрибуты html5, чтобы сделать это легко. (обязательные атрибуты-заполнители)

Попробуйте код ниже.

 <!doctype html>
    <html lang="en">
    <head>
      <title> Lab 6 - Task 2 </title>
      <style>
        span {
          padding-left: 10px;
          display: block;
          float: left;
          width: 20%;
        }
        button { margin-left: 10px; }
        body {
          width: 80%; margin: auto; font-family: sans-serif;
          border: 1px solid black;
        }
      </style>
      <meta charset="utf-8">
    </head>
    <body>
        <form id="myForm" method="get">
          <h1> Form Submit </h1>
          <p><span>Name:</span> <input id="input1" placeholder="Enter Name" name="Name" required></p>
          <p><span>Student Id:</span> <input id="input2" placeholder="Enter Student ID" name="StudentID" required></p>
          <p><span>Email:</span> <input id="input3" placeholder="Enter Email" name="Email" required></p>
          <p>
            <button id="submitButton" type="submit">Submit </button>
            <input type="reset" value="Reset"/>
          </p>
          <p style="color:red" id="ErrorMessage"> &nbsp; </p>
        </form>
    </body>
    </html>
0 голосов
/ 05 ноября 2018

Исправьте это:

<form id="myForm" method="get" onsubmit="checkforblank()">
</form>
Смотрите здесь

Нет необходимости в операторе возврата

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...