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

ulmd4ohb  于 2023-03-07  发布在  jQuery
关注(0)|答案(3)|浏览(102)

我试图显示一个错误消息,每当表单输入域name是空的,但似乎它返回什么;我的代码有什么问题吗?
我正在处理www.example.com服务器。codepen.io server.
我已经包含了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",但没有返回任何内容。

dgsult0t

dgsult0t1#

在我看来,你肯定需要做一些调整
1.根据此规范,将所有误差范围从id='error'更改为class='error'
1.您必须将提交按钮从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>
cvxl0en2

cvxl0en22#

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

  1. firstName是一个文本字段,它没有提交事件,您是否尝试将该事件分配给表单?
  2. id在整个html中应该是unqiue。在您的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>
1cosmwyk

1cosmwyk3#

首先,将提交按钮类型更改为"button",因为您仍然使用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>

相关问题