2

I'm new here, and this is the first question to be asked by me.

I'm a beginner in programming and coding, I'm trying to make a basic system to view students' marks by entering their school numbers. Here's my code:-

<html>
<body>
<head>
<title>Test</title>
</head>

<input type="text" id="txtjob">
<button onclick="getnatega()">OK</button>


<script>
function getnatega() {
if (txtjob == 2386) {
window.location.href = "www.ex.com";
}
}
</script>
</body>
</html>

But whenever i click the "OK" button nothing happens. I'd be thankful to whoever helps me.

4 Answers 4

2

You need to access the element itself and take the value out of it. The result is a string.

function getnatega() {
    if (document.getElementById('txtjob').value === '2386') {
        window.location.href = "www.ex.com";
    }
}
<input type="text" id="txtjob">
<button onclick="getnatega()">OK</button>

Sign up to request clarification or add additional context in comments.

Comments

1

This is the correct code

<html>

<head>
<title>Test</title>
<script type="text/javascript">
function getnatega() 
{
  var a=document.getElementById('txtjob').value;

  if ( a == 2386) 
  {
    window.location.href = "www.ex.com";
  }
}
</script>
</head>
<body>

<input type="text" id="txtjob">
<button onclick="getnatega()">OK</button>


</body>
</html>

2 Comments

Looks sound to me?
Since the result is string and you use non quoted 2386 it shouldn't, if to use ===, which I missed you didn't ... removed comment and down vote
0

You need to use the document API to get reference to the element in JavaScript. You can assign that element to a variable so you don't have to call the method every time.

var txtJob = document.getElementById('txtjob');
function getnatega() {
  if (txtJob.value == '2386') {
    window.location.href = "www.ex.com";
  }
}

There is a quirk in some browsers where the engine will define a global variable with the ID of the element. You may be able to get away with just if (window.txtjob.value == '2386') but even if it works I don't recommend using it because it's not a standardized behavior and all browsers may not do the same thing. All of them will have the document API though and you can use that to properly get reference to the element as shown above.

1 Comment

Thanks, I appreciate your effort helping me.
0

Nothing happens because txtjob is undefined. If you want to get the input's value, it's in document.getElementById("txtjob").value.

1 Comment

It is more than enough. Asker should do some work, I prefer to explain than to give code to copy and paste.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.