<!DOCTYPE html>
<html>
<body bgcolor = "eeeeee">
<p> Add Section </p>
<label>Fir No :</label>
<input id="txt1" type="text"/></br></br>
<label>Sec No :</label>
<input id="txt2" type="text"/></br></br>
<input type="button" name="Add" value="Add" onclick="addTwoNumber()"/>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = Date();
}
<!-- addition of two numbers-->
function addTwoNumber(){
var a = document.getElementById("txt1").value;
var b = document.getElementById("txt2").value;
var x = Number(a) + Number(b);
document.getElementById("demo").innerHTML = "Add Value: " + x;
}
</script>
</body>
</html>
我已经在此代码中编写了代码,如果他输入的不是数字,我无法提醒用户,如果他留空而没有填写值,则无法提醒用户
答案 0 :(得分:0)
使用 isNaN() 检查有效号码。
function addTwoNumber(){
var a = document.getElementById("txt1").value;
var b = document.getElementById("txt2").value;
if(a == "")
{
alert("enter txt1 value");
return;
}
if(b == ""){
alert("enter txt2 value");
return;}
if(isNaN(a)){
alert("enter valid number txt1 value");
return;}
if(isNaN(b)){
alert("enter valid number txt2 value");
return;}
var x = Number(a) + Number(b);
document.getElementById("demo").innerHTML = "Add Value: " + x;
}
答案 1 :(得分:0)
尝试以下代码:
<!DOCTYPE html>
<html>
<body bgcolor = "eeeeee">
<p> Add Section </p>
<label>Fir No :</label>
<input id="txt1" type="text"/></br></br>
<label>Sec No :</label>
<input id="txt2" type="text"/></br></br>
<input type="button" name="Add" value="Add" onclick="addTwoNumber()"/>
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = Date();
}
<!-- addition of two numbers-->
function addTwoNumber(){
var a = document.getElementById("txt1").value;
var b = document.getElementById("txt2").value;
if (a == "" || b == "")
{
alert('Please enter any number');
return;
}
if (isNaN(a) || isNaN(b))
{
alert('Please enter any number');
return;
}
var x = Number(a) + Number(b);
document.getElementById("demo").innerHTML = "Add Value: " + x;
}
</script>
</body>
</html>