skip to Main Content

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


  1. You can try to check if it is Nan and if the value is more than 0.

      let data = [9, 45, 2, 8, 45, 23, 7, 78, 0, 11, 41, 77];
    
            function getElement() {
                let ele = parseInt(document.getElementById('element').value);
    
                if (!isNaN(ele) && ele >= 0 && ele < data.length) {
                    alert(data[ele]);
                } else {
                    alert("Please Enter a valid input");
                }
            }
    

    if statement is checking if the value is null and if it is more than 0, else it gives alert.

    Login or Signup to reply.
  2. 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")

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search