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).
-
p
doesn't have avalue
property. UsetextContent
orinnerText
to check if the element contains any text, to check if it contains any child HTML theninnerHTML
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
2 Answers
Reset to default 3It'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>