Подтвердить что ты не робот

Проверка JavaScript для пустого поля ввода

Приветствие, у меня есть это поле ввода <input name="question"/> Я хочу вызвать функцию IsEmpty при отправке, нажав кнопку отправки.

Я попробовал код ниже, но не работал. любой совет?!

<html>

<head>
  <title></title>
  <meta http-equiv="Content-Type" content="text/html; charset=unicode" />
  <meta content="CoffeeCup HTML Editor (www.coffeecup.com)" name="generator" />
</head>

<body>


  <script language="Javascript">
    function IsEmpty() {

      if (document.form.question.value == "") {
        alert("empty");
      }
      return;
    }
  </script>
  Question: <input name="question" /> <br/>

  <input id="insert" onclick="IsEmpty();" type="submit" value="Add Question" />

</body>

</html>
4b9b3361

Ответ 1

<script type="text/javascript">
  function validateForm() {
    var a = document.forms["Form"]["answer_a"].value;
    var b = document.forms["Form"]["answer_b"].value;
    var c = document.forms["Form"]["answer_c"].value;
    var d = document.forms["Form"]["answer_d"].value;
    if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {
      alert("Please Fill All Required Field");
      return false;
    }
  }
</script>

<form method="post" name="Form" onsubmit="return validateForm()" action="">
  <textarea cols="30" rows="2" name="answer_a" id="a"></textarea>
  <textarea cols="30" rows="2" name="answer_b" id="b"></textarea>
  <textarea cols="30" rows="2" name="answer_c" id="c"></textarea>
  <textarea cols="30" rows="2" name="answer_d" id="d"></textarea>
</form>

Ответ 2

Смотрите рабочий пример здесь


Вам не хватает обязательного элемента <form>. Вот как должен выглядеть ваш код:

function IsEmpty() {
  if (document.forms['frm'].question.value === "") {
    alert("empty");
    return false;
  }
  return true;
}
<form name="frm">
  Question: <input name="question" /> <br />
  <input id="insert" onclick="return IsEmpty();" type="submit" value="Add Question" />
</form>

Ответ 3

Поле ввода может иметь пробелы, вы хотите предотвратить это:

function isEmpty(str){
    return !str.replace(/\s+/, '').length;
}

Пример:

function isEmpty(str){
    return !str.replace(/\s+/, '').length;
}

document.getElementById("name").addEventListener("input", function() {
  if( isEmpty(this.value) ) {
     console.log( "NAME IS EMPTY!" )
  }
});
<input id="name" type="text">

Ответ 4

Я хотел бы добавить обязательный атрибут в случае, если пользователь отключил javascript:

<input type="text" id="textbox" required/>

Он работает во всех современных браузерах.

Ответ 5

if(document.getElementById("question").value.length == 0)
{
    alert("empty")
}

Ответ 6

Добавьте идентификатор "вопрос" к элементу ввода, а затем попробуйте следующее:

   if( document.getElementById('question').value === '' ){
      alert('empty');
    }

Причина, по которой ваш текущий код не работает, заключается в том, что у вас нет тега FORM. Кроме того, поиск с использованием "имени" не рекомендуется в качестве устаревшего.

См. @Paul Dixon ответ в этом сообщении: Является ли атрибут 'name' устаревшим для <a> якорные метки?

Ответ 7

if(document.getElementById("question").value == "")
{
    alert("empty")
}

Ответ 8

Просто добавьте тег идентификатора в элемент ввода... т.е.:

и проверьте значение элемента в javascript:

document.getElementById( "вопрос" ). Значение

О, да, получите firefox/firebug. Это единственный способ сделать javascript.

Ответ 9

<pre>
       <form name="myform" action="saveNew" method="post" enctype="multipart/form-data">
           <input type="text"   id="name"   name="name" /> 
           <input type="submit"/>
       </form>
    </pre>

<script language="JavaScript" type="text/javascript">
  var frmvalidator = new Validator("myform");
  frmvalidator.EnableFocusOnError(false);
  frmvalidator.EnableMsgsTogether();
  frmvalidator.addValidation("name", "req", "Plese Enter Name");
</script>

Ответ 11

Мое решение ниже в es6, потому что я использовал const если вы предпочитаете es5, вы можете заменить все const на var.

const str = "       Hello World!        ";
// const str = "                     ";

checkForWhiteSpaces(str);

function checkForWhiteSpaces(args) {
    const trimmedString = args.trim().length;
    console.log(checkStringLength(trimmedString))     
    return checkStringLength(trimmedString)        
}

// If the browser doesn't support the trim function
// you can make use of the regular expression below

checkForWhiteSpaces2(str);

function checkForWhiteSpaces2(args) {
    const trimmedString = args.replace(/^\s+|\s+$/gm, '').length;
    console.log(checkStringLength(trimmedString))     
    return checkStringLength(trimmedString)
}

function checkStringLength(args) {
    return args > 0 ? "not empty" : "empty string";
}