My Program Successfull Run but Not Resolve Negative Number Input in Html input field Show message in alert Box Undefined Hot to Run else Conditon
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array Traversing</title>
<script>
let data = [9,45,2,8,45,23,7,78,0,11,41,77];
function getElement(){
let ele = document.getElementById('element').value;
if(ele<data.length && typeof parseInt(ele) === "number"){
alert(data[ele]);
}else{
alert("Please Enter valid Input");
}
}
</script>
</head>
<body>
<input type="text" name="" id="element" />
<button onclick="getElement()">Get Element</button>
</body>
</html>
My Program Successfull Run but Not Resolve Negative Number Input in Html input field Show message in alert Box Undefined Hot to Run else Conditon
2
Answers
You can try to check if it is
Nan
and if the value is more than 0.if
statement is checking if the value isnull
and if it is more than 0, else it gives alert.You can use same code with one change
you have to add ele >= 0 conditon in if statement.
Like if(ele<data.length && ele>=0 && typeof parseInt(ele) === "number")