0

I have this tag on a webpage

<input type="hidden" name="ctl00_ed3327f9_e1db_40db_9d66_15946cead7ae_STATEFIELD" id="ctl00_0g_ed3327f9_e1db_40db_9d66_15946cead7ae__STATEFIELD" value="0" />

I want to modify its value, i.e. from value="0" to value="1" using JavaScript. I have tried:

document.getElementById("ctl00_0g_ed3327f9_e1db_40db_9d66_15946cead7ae__STATEFIELD"); 

but it returns null. I guess that's because it is a hidden field

4 Answers 4

1

If getElementById is returning null, it is likely because you're running the script before the element has been created.

Either move your script to the bottom of the page, just inside the closing </body> tag:

<body>

    <!-- page content -->

    <script type="text/javascript">
        document.getElementById("ctl00_0g_ed3327f9_e1db_40db_9d66_15946cead7ae__STATEFIELD").value = 1; 
    </script>
</body>

or run in inside a window.onload handler:

<script type="text/javascript">
    window.onload = function() {
        document.getElementById("ctl00_0g_ed3327f9_e1db_40db_9d66_15946cead7ae__STATEFIELD").value = 1; 
    };
</script>
Sign up to request clarification or add additional context in comments.

4 Comments

noops .... using this the page load stucks in infinite looping when the object is null// the error is object reference is null;; .....
@Umbrella: Infinite loop? Did the selector find the element, or not? If there's a loop, that's another issue.
no there is no loop in my code .;;; & selector didn't find anything ;; i just want to toggle the value . nothing else (there is no other code ) ** 1 thing more i want to tell u // its a sharepoint 2010 webpart page .
@Umbrella: That's very strange that it returns null. Here's an example that shows it should work.
0

For .NET 3.5 and earlier, use

document.getElementById('<%= controlName.ClientID %>');

For .NET 4.0, set the ClientIDMode on the control to Static.

Comments

0

I just tested your code and it works. hidden shouldn't make a difference. I am guessing the problem might be that you are trying to run getElementById before the element has been loaded onto the page?

2 Comments

... hmm this is the case .. so how to overcome it ...??
patrick_dw's advice is spot on here. Either you need to move the script below the part of the page with the element, or you need to wrap your JS into an onload so that it doesn't run until the page is loaded.
0

You've added the tag, so I presume your are using it. This would be your solution:

$("#ctl00_0g_ed3327f9_e1db_40db_9d66_15946cead7ae__STATEFIELD").val("1");

1 Comment

getElementById does not need the #.

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.