admin管理员组

文章数量:1431406

I have the following in my project:

function check() {
  var empt = document.getElementById('xyz1').value;

  if (empt == "") {
    alert("Please input a Value");
    return false;
  } else {
    return true;
  }
}
<a href="test.html" role="button" name="weiter" id="weiter" onclick="check();">Go</a>
<p id="xyz1"></p>

I have the following in my project:

function check() {
  var empt = document.getElementById('xyz1').value;

  if (empt == "") {
    alert("Please input a Value");
    return false;
  } else {
    return true;
  }
}
<a href="test.html" role="button" name="weiter" id="weiter" onclick="check();">Go</a>
<p id="xyz1"></p>

Something I am doing wrong. I always get to the page test.html. The check is not working. Is it even possible, to check if a p tag is empty?
Goal is, if there is nothing in the p tag to get an alert and if there is a string or number getting to the linked page test.html I would like to work in pure JavaScript (no jQuery).

Share Improve this question edited Dec 31, 2017 at 14:07 Andreas 21.9k7 gold badges51 silver badges58 bronze badges asked Dec 31, 2017 at 14:02 peachmeierpeachmeier 1332 gold badges2 silver badges7 bronze badges 4
  • p doesn't have a value property. Use textContent or innerText to check if the element contains any text, to check if it contains any child HTML then innerHTML will suffice. – Deepak Kamat Commented Dec 31, 2017 at 14:03
  • 1 use innerHTML function – madhur Commented Dec 31, 2017 at 14:03
  • @madhur innerHTML isn’t a function. – Sebastian Simon Commented Dec 31, 2017 at 17:47
  • I mean innerHTML property on element – madhur Commented Dec 31, 2017 at 19:18
Add a ment  | 

2 Answers 2

Reset to default 3

It's innerHTML instead of value. Also, check for null.

function check() {

  var empt = document.getElementById('xyz1').innerHTML;
  if (empt == null || empt == "")
  {
  alert("Please input a Value");
  return false;
  }
  else 
  {
  return true; 
  }
  }
<a href="test.html" role="button" name="weiter" id="weiter" onclick="check();">Go</a>
<p id="xyz1"></p>

		function check() {
			event.preventDefault();
		  var empt = document.getElementById('xyz1').innerHTML;
		  if (empt == null || empt == "")
		  {
		    alert("Please input a Value");
		    return false;
		  }
		  else 
		  {
		  	return true; 
		  }
		}
<a href="test.html" role="button" name="weiter" id="weiter" onclick="check();">Go</a>
<p id="xyz1"></p>

Function must be event prevent default otherwise run href after on click event.

Another Method

onclick="return check()"

		function check() { 
		  var empt = document.getElementById('xyz1').innerHTML;
		  if (empt == null || empt == "")
		  {
		    alert("Please input a Value");
		    return false;
		  }
		  else 
		  {
		  	return true; 
		  }
		}
<a href="test.html" role="button" name="weiter" id="weiter" onclick="return check();">Go</a>
<p id="xyz1"></p>

本文标签: JavaScript check if html p tag is emptyStack Overflow