0

why i am getting runtime error in javascript at

var ClientID = document.getElementById("ClientIDTextBox").value;

and my code is:

<script type="text/javascript">
    var ClientID = document.getElementById("ClientIDTextBox").value;
    if (ClientID == "") {
        alert("Please enter ClientID")
      }
</script>

please help me

2
  • 2
    maybe element with id ClientIDTextBox wasn't found? Commented Sep 21, 2011 at 16:23
  • 1
    Let me guess, you put this script before the element you're trying to get the ID of? Commented Sep 21, 2011 at 16:23

2 Answers 2

3

You are likely getting a runtime error because the call document.getElementById is returning null. The attempt to get the property value on null leads to an error.

Try the following instead

var element = document.getElementById('ClientIDTextBox');
if (element) {
  var ClientID = element.value;
  ...
}

The root cause though is likely that your javascript is running before the DOM is loaded and hence your element with id ClientIDTextBox is not available. Ensure your javascript runs after the DOM is loaded to prevent this problem.

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

2 Comments

Any logical reason why this is a bad answer? Why the downvote?
@Mike, my first version had getElementById returning undefined instead of null on error. I've since corrected that but it could be the cause of the original downvote.
1
<script type="text/javascript">
    var ClientID = document.getElementById("ClientIDTextBox");
    if (ClientID == null || ClientID.value == "") {
        alert("Please enter ClientID")
      }
</script>

Comments

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.