输入字段为空时,我无法显示错误消息

时间:2019-06-05 06:10:24

标签: javascript jquery html

每当表单输入字段name为空,但似乎什么也不返回时,我试图显示一条错误消息。我的代码有什么问题?

我正在codepen.io服务器上工作。
我包含了jquery 3.4.1而不是jquery 3.3.1,但似乎也无法正常工作。

$(document).ready(function() {
  var firstName = document.forms["myForm"]["name"];

  var mail = document.forms["myForm"]["email"];
  var errorMessage = document.forms["myForm"]["error"];

  function check(event) {
    event.preventDefault();
    if (firstName.value == '' || !firstName.value.length) {
      console.log("here");
      errorMessage.innerText = "This is invalid name";
    } else {
      errorMessage.innerText = '';
    }
  }
  firstName.addEventListener('submit', check);
});
<!DOCTYPE html>
<html lang="en">

<head>
  <title>FCC:Survey Form</title>
  <meta charset="utf-8">
  <meta name="description" content="survey form helps user fill in  a questionnaire" />
  <meta name="author" content="lily bani, david jhonson" />
  <meta name="description" content="survey, form, questionnaire" />
  <meta http-equiv="refresh" content="30" />
  <meta http-equiv="Content-Type" content="text/html; charset=en-US" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- add bootstrap to the website -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <!-- add fonts to make it stylish -->
  <link href="https://fonts.googleapis.com/css?family=Great+Vibes&display=swap" rel="stylesheet">
  <link type="javascript" src="plain.js" />

</head>

<body class="bigBox">
  <h1 id="title">Survey Form</h1>
  <div class="container">
    <p id="description">Let us know how to improve FreeCodeCamp</p>
    <form id="survey-form" action="" method="post" name="myForm">
      <label for="name" id="name-label">
*Name:  <input type="text" name="name" id="name" placeholder="Enter your name"/>
      <span id="error" name="error"> </span><br/>
    </label>
      <label for="email" id="email-label">
 *Email:  <input type="email" id="email"  name="email" placeholder="Enter your email"/><span id="error" name="error"> </span><br/>
    </label>
      <label for="age" id="number-label">
  *Age: <input type="number" name="number" id="number" min="18" max="35" placeholder="Age" />
    </label>
      <p id="one">Which option best describes your current role?</p>
      <select id="dropdown1">
        <option value="select an option" disabled>select an option</option>
        <option value="student">student</option>
        <option value="full time job">full time job</option>
        <option value="full time learner">full time learner</option>
        <option value="prefer not to say">prefer not to say</option>
        <option value="others">others</option>
      </select>
      <div class="two">
        <p>* How likely is that you would recommend freeCodeCamp to a friend?</p>
        <input type="radio" name="choice" value="Definitely">Definitely<br>
        <input type="radio" name="choice" value="maybe">Maybe<br>
        <input type="radio" name="choice" value="notsure">Not Sure
      </div>
      <p id="three">What do you like most in FCC:</p>
      <select id="dropdown2">
        <option value="select an option" disabled>select an option</option>
        <option value="challenegs">challenges</option>
        <option value="projects">projects</option>
        <option value="community">community</option>
        <option value="opensource">open source</option>
      </select>

      <p id="four">Things that should be improved in the future (Check all that apply):</p>
      <fieldset>
        <div>
          <input type="checkbox" name="sources" value="Front-end Projects"><label for="go">Front end Projects</label><br>
          <input type="checkbox" name="sources" value="Back-end Projects"><label for="go1">Back-end Projects</label><br>
          <input type="checkbox" name="sources" value="Data Visualization"><label for="go2">Data Visualization</label><br>
          <input type="checkbox" name="sources" value="Challenges"><label for="go3">Challenges</label><br>
          <input type="checkbox" name="sources" value="Open Source Community"><label for="go4">Open Source Community</label><br>
          <input type="checkbox" name="sources" value="Gitter help rooms"><label for="go6">Gitter help rooms</label><br>
          <input type="checkbox" name="sources" value="videos"><label for="go7">videos</label><br>
          <input type="checkbox" name="sources" value="city meetups"><label for="go8">city meetups</label><br>
          <input type="checkbox" name="sources" value="wiki"><label for="go9">wiki</label><br>
          <input type="checkbox" name="sources" value="forum"><label for="go10">forum</label><br>
          <input type="checkbox" name="sources" value="additional courses"><label for="go11">additional courses</label><br>
        </div>
      </fieldset>
      <p id="text_me">Any comments or Suggestions:</p>
      <textarea id="textarea_now" rows="3" cols="25" placeholder="enter your comment here">
</textarea>

      <input type="submit" id="button_me" class="btn btn-info" value="Submit">
    </form>
  </div>
  <!-- optional javascript... using jquery and popper.js for interactive mode -->
  <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
  <link type="text/css" src="plain.css" />

  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>

</html>

它应该返回错误"This is invalid name",但不返回任何内容。

3 个答案:

答案 0 :(得分:1)

  1. 将行替换为<script src="plain.js" type="text/javascript"></script>以引用外部js文件
  2. 您应该在自己的代码之前引用依赖项,即jQuery。 jQuery参考位于html的末尾,但是plain.js在第一行需要$。您将遇到$ is not defined错误

  3. firstName是一个文本字段,没有提交事件,您是否要将该事件分配给表单?

  4. id在整个html中应该是不存在的。您的error中有多个ID

/**
 * 
 */

$(document).ready(function() {
	var firstName = document.forms["myForm"]["name"];

	var mail = document.forms["myForm"]["email"];

	function check(event) {
		event.preventDefault();
		var errorMessage = $(firstName).next('.error');
		if (firstName.value == '' || !firstName.value.length) {
			console.log("here");
			errorMessage.html("This is invalid name");

		} else {
			errorMessage.html("");
		}
	}

	$('#survey-form').on('submit', check);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<title>FCC:Survey Form</title>
<meta charset="utf-8">
<meta name="description"
	content="survey form helps user fill in  a questionnaire" />
<meta name="author" content="lily bani, david jhonson" />
<meta name="description" content="survey, form, questionnaire" />
<meta http-equiv="refresh" content="30" />
<meta http-equiv="Content-Type" content="text/html; charset=en-US" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- add bootstrap to the website -->
<link rel="stylesheet"
	href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
	integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
	crossorigin="anonymous">
<!-- add fonts to make it stylish -->
<link
	href="https://fonts.googleapis.com/css?family=Great+Vibes&display=swap"
	rel="stylesheet">



</head>
<body class="bigBox">
	<h1 id="title">Survey Form</h1>
	<div class="container">
		<p id="description">Let us know how to improve FreeCodeCamp</p>
		<form id="survey-form" action="" method="post" name="myForm">
			<label for="name" id="name-label"> *Name: <input type="text"
				name="name" id="name" placeholder="Enter your name" /> <span
				class="error" name="error"> </span><br />
			</label> <label for="email" id="email-label"> *Email: <input
				type="email" id="email" name="email" placeholder="Enter your email" /><span
				class="error" name="error"> </span><br />
			</label> <label for="age" id="number-label"> *Age: <input
				type="number" name="number" id="number" min="18" max="35"
				placeholder="Age" />
			</label>
			<p id="one">Which option best describes your current role?</p>
			<select id="dropdown1">
				<option value="select an option" disabled>select an option</option>
				<option value="student">student</option>
				<option value="full time job">full time job</option>
				<option value="full time learner">full time learner</option>
				<option value="prefer not to say">prefer not to say</option>
				<option value="others">others</option>
			</select>
			<div class="two">
				<p>* How likely is that you would recommend freeCodeCamp to a
					friend?</p>
				<input type="radio" name="choice" value="Definitely">Definitely<br>
				<input type="radio" name="choice" value="maybe">Maybe<br>
				<input type="radio" name="choice" value="notsure">Not Sure
			</div>
			<p id="three">What do you like most in FCC:</p>
			<select id="dropdown2">
				<option value="select an option" disabled>select an option</option>
				<option value="challenegs">challenges</option>
				<option value="projects">projects</option>
				<option value="community">community</option>
				<option value="opensource">open source</option>
			</select>

			<p id="four">Things that should be improved in the future (Check
				all that apply):</p>
			<fieldset>
				<div>
					<input type="checkbox" name="sources" value="Front-end Projects"><label
						for="go">Front end Projects</label><br> <input
						type="checkbox" name="sources" value="Back-end Projects"><label
						for="go1">Back-end Projects</label><br> <input
						type="checkbox" name="sources" value="Data Visualization"><label
						for="go2">Data Visualization</label><br> <input
						type="checkbox" name="sources" value="Challenges"><label
						for="go3">Challenges</label><br> <input type="checkbox"
						name="sources" value="Open Source Community"><label
						for="go4">Open Source Community</label><br> <input
						type="checkbox" name="sources" value="Gitter help rooms"><label
						for="go6">Gitter help rooms</label><br> <input
						type="checkbox" name="sources" value="videos"><label
						for="go7">videos</label><br> <input type="checkbox"
						name="sources" value="city meetups"><label for="go8">city
						meetups</label><br> <input type="checkbox" name="sources"
						value="wiki"><label for="go9">wiki</label><br> <input
						type="checkbox" name="sources" value="forum"><label
						for="go10">forum</label><br> <input type="checkbox"
						name="sources" value="additional courses"><label
						for="go11">additional courses</label><br>
				</div>
			</fieldset>
			<p id="text_me">Any comments or Suggestions:</p>
			<textarea id="textarea_now" rows="3" cols="25"
				placeholder="enter your comment here">
</textarea>

			<input type="submit" id="button_me" class="btn btn-info"
				value="Submit">
		</form>
	</div>
	<!-- optional javascript... using jquery and popper.js for interactive mode -->
	<script src="https://code.jquery.com/jquery-3.4.1.min.js"
		integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
		crossorigin="anonymous"></script>
	<link type="text/css" src="plain.css" />

	<script
		src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"
		integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1"
		crossorigin="anonymous"></script>
	<script
		src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
		integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
		crossorigin="anonymous"></script>

	<script src="plain.js" type="text/javascript"></script>


</body>
</html>

答案 1 :(得分:1)

从我的角度来看,您肯定需要进行一些调整

  1. 更改所有错误范围。 class='error',而不是id='error'。 根据{{​​3}}。
  2. 您必须将“提交”按钮从type='submit'更改为type='button'。此更改将帮助您验证整个表单,并获得对应用程序流程的更多控制。

最后在这里,您可以找到针对表单的全新验证功能:

$(document).ready(function() {
	const $surveyForm = $('#survey-form');
  $('#button_me').on('click', function(){
		const $name = $('#name');
		const $error = $name.next();
		const isNameValid = $name.val().length > 0;
		$error.text(isNameValid ? '' : 'This is invalid name');
		
				if(isNameValid) {
					$surveyForm.submit();
				}
	});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1 id="title">Survey Form</h1>
  <div class="container">
    <p id="description">Let us know how to improve FreeCodeCamp</p>
    <form id="survey-form" action="" method="post" name="myForm">
      <label for="name" id="name-label">
*Name:  <input type="text" name="name" id="name" placeholder="Enter your name"/>
      <span class="error" name="error"> </span><br/>
    </label>
      <label for="email" id="email-label">
 *Email:  <input type="email" id="email"  name="email" placeholder="Enter your email"/><span class="error" name="error"> </span><br/>
    </label>
      <label for="age" id="number-label">
  *Age: <input type="number" name="number" id="number" min="18" max="35" placeholder="Age" />
    </label>
      <p id="one">Which option best describes your current role?</p>
      <select id="dropdown1">
        <option value="select an option" disabled>select an option</option>
        <option value="student">student</option>
        <option value="full time job">full time job</option>
        <option value="full time learner">full time learner</option>
        <option value="prefer not to say">prefer not to say</option>
        <option value="others">others</option>
      </select>
      <div class="two">
        <p>* How likely is that you would recommend freeCodeCamp to a friend?</p>
        <input type="radio" name="choice" value="Definitely">Definitely<br>
        <input type="radio" name="choice" value="maybe">Maybe<br>
        <input type="radio" name="choice" value="notsure">Not Sure
      </div>
      <p id="three">What do you like most in FCC:</p>
      <select id="dropdown2">
        <option value="select an option" disabled>select an option</option>
        <option value="challenegs">challenges</option>
        <option value="projects">projects</option>
        <option value="community">community</option>
        <option value="opensource">open source</option>
      </select>

      <p id="four">Things that should be improved in the future (Check all that apply):</p>
      <fieldset>
        <div>
          <input type="checkbox" name="sources" value="Front-end Projects"><label for="go">Front end Projects</label><br>
          <input type="checkbox" name="sources" value="Back-end Projects"><label for="go1">Back-end Projects</label><br>
          <input type="checkbox" name="sources" value="Data Visualization"><label for="go2">Data Visualization</label><br>
          <input type="checkbox" name="sources" value="Challenges"><label for="go3">Challenges</label><br>
          <input type="checkbox" name="sources" value="Open Source Community"><label for="go4">Open Source Community</label><br>
          <input type="checkbox" name="sources" value="Gitter help rooms"><label for="go6">Gitter help rooms</label><br>
          <input type="checkbox" name="sources" value="videos"><label for="go7">videos</label><br>
          <input type="checkbox" name="sources" value="city meetups"><label for="go8">city meetups</label><br>
          <input type="checkbox" name="sources" value="wiki"><label for="go9">wiki</label><br>
          <input type="checkbox" name="sources" value="forum"><label for="go10">forum</label><br>
          <input type="checkbox" name="sources" value="additional courses"><label for="go11">additional courses</label><br>
        </div>
      </fieldset>
      <p id="text_me">Any comments or Suggestions:</p>
      <textarea id="textarea_now" rows="3" cols="25" placeholder="enter your comment here">
</textarea>

      <input type="button" id="button_me" class="btn btn-info" value="Submit">
    </form>
  </div>

答案 2 :(得分:0)

首先,将提交按钮类型更改为“按钮”,因为您仍使用event.preventDefault()

然后。您可以使用html5验证来检查字段值。您需要向要检查的文件添加require属性。如果要验证字段并显示错误消息,可以使用form.reportValidity()方法,而form.checkValidity()仅返回布尔值。

// you have to be consistent in code style.
// use native methods for load event as you use native methods to get form element


// You can set custom validation messages or you can use html5 attributes to set rules

let validationMessages = {
  'name': {
    'invalid': 'Please provide a valid name'
  },
  'email': {
    'invalid': 'Please provide a valid email'
  }
}

document.addEventListener('DOMContentLoaded', e => {
  let form = document.forms["myForm"]
  let sbmButton = document.querySelector('#submit-form-button')
  let requiredFields = [...form.querySelectorAll('[required]')]

  // you can put event listener here because functions declared as below bubble up to top of the script during interpretation 
  // to use custom error messages change "check" to "checkCustom"
  sbmButton.addEventListener('click', checkCustom);

  // clear error message on typing
  requiredFields.forEach(field => {
    field.addEventListener('input', () => {
      let errorField = document.querySelector(`#${field.name}-error`)
      errorField.textContent = ''
      errorField.classList.add('hidden')
    })
  })

  // here is the way with using "require" attribute and html5 validation
  function check(event) {
    if (!form.reportValidity()) {
      return false
    }
    // do something if form is valid
  }

  function checkCustom(event) {

    requiredFields.forEach(field => {
      let errorFiled = form.querySelector(`#${field.name}-error`)
      let errorText = ''
      if (!field.value.length) {
        errorText = getEmptyFieldMessage(field.name)
      }
      // check if email or name contains not allowed characters
      else if (!field.checkValidity()) {
        errorText = validationMessages[field.name]['invalid']
      }
      errorFiled.classList.remove('hidden')
      errorFiled.textContent = errorText
    })
  }

  function getEmptyFieldMessage(fieldName) {
    return `The field "${fieldName}" can not be empty.`
  }

});
.error-message {
  display: block;
  color: red;
}

.hidden {
  display: none;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <title>FCC:Survey Form</title>
  <meta charset="utf-8">
  <meta name="description" content="survey form helps user fill in  a questionnaire" />
  <meta name="author" content="lily bani, david jhonson" />
  <meta name="description" content="survey, form, questionnaire" />
  <meta http-equiv="refresh" content="30" />
  <meta http-equiv="Content-Type" content="text/html; charset=en-US" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <!-- add bootstrap to the website -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
  <!-- add fonts to make it stylish -->
  <link href="https://fonts.googleapis.com/css?family=Great+Vibes&display=swap" rel="stylesheet">
  <link type="javascript" src="plain.js" />

</head>

<body class="bigBox">
  <h1 id="title">Survey Form</h1>
  <div class="container">
    <p id="description">Let us know how to improve FreeCodeCamp</p>
    <form id="survey-form" action="" method="post" name="myForm">
      <label for="name" id="name-label">
*Name:  <input type="text" name="name" id="name" placeholder="Enter your name" required/>
      <span id="name-error" class="error-message hidden" name="error"> </span><br/>
    </label>
      <label for="email" id="email-label">
 *Email:  <input type="email" id="email"  name="email" placeholder="Enter your email" required/><span id="email-error" class="error-message hidden" name="error"> </span><br/>
    </label>
      <label for="age" id="number-label">
  *Age: <input type="number" name="number" id="number" min="18" max="35" placeholder="Age" />
    </label>
      <p id="one">Which option best describes your current role?</p>
      <select id="dropdown1">
        <option value="select an option" disabled>select an option</option>
        <option value="student">student</option>
        <option value="full time job">full time job</option>
        <option value="full time learner">full time learner</option>
        <option value="prefer not to say">prefer not to say</option>
        <option value="others">others</option>
      </select>
      <div class="two">
        <p>* How likely is that you would recommend freeCodeCamp to a friend?</p>
        <input type="radio" name="choice" value="Definitely">Definitely<br>
        <input type="radio" name="choice" value="maybe">Maybe<br>
        <input type="radio" name="choice" value="notsure">Not Sure
      </div>
      <p id="three">What do you like most in FCC:</p>
      <select id="dropdown2">
        <option value="select an option" disabled>select an option</option>
        <option value="challenegs">challenges</option>
        <option value="projects">projects</option>
        <option value="community">community</option>
        <option value="opensource">open source</option>
      </select>

      <p id="four">Things that should be improved in the future (Check all that apply):</p>
      <fieldset>
        <div>
          <input type="checkbox" name="sources" value="Front-end Projects"><label for="go">Front end Projects</label><br>
          <input type="checkbox" name="sources" value="Back-end Projects"><label for="go1">Back-end Projects</label><br>
          <input type="checkbox" name="sources" value="Data Visualization"><label for="go2">Data Visualization</label><br>
          <input type="checkbox" name="sources" value="Challenges"><label for="go3">Challenges</label><br>
          <input type="checkbox" name="sources" value="Open Source Community"><label for="go4">Open Source Community</label><br>
          <input type="checkbox" name="sources" value="Gitter help rooms"><label for="go6">Gitter help rooms</label><br>
          <input type="checkbox" name="sources" value="videos"><label for="go7">videos</label><br>
          <input type="checkbox" name="sources" value="city meetups"><label for="go8">city meetups</label><br>
          <input type="checkbox" name="sources" value="wiki"><label for="go9">wiki</label><br>
          <input type="checkbox" name="sources" value="forum"><label for="go10">forum</label><br>
          <input type="checkbox" name="sources" value="additional courses"><label for="go11">additional courses</label><br>
        </div>
      </fieldset>
      <p id="text_me">Any comments or Suggestions:</p>
      <textarea id="textarea_now" rows="3" cols="25" placeholder="enter your comment here">
</textarea>

      <button type="button" id="submit-form-button" class="btn btn-info">Submit</button>
    </form>
  </div>
  <!-- optional javascript... using jquery and popper.js for interactive mode -->
  <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
  <link type="text/css" src="plain.css" />

  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>

</html>