I have a JavaScript function to which I pass a parameter. The parameter represents the id of an element (a hidden field) in my web page. I want to change the value of this element.
function myFunc(variable) { var s = document.getElementById(variable); s.value = 'New value' } When I do this, I get an error that the value cannot be set because the object is null. But I know the object is not null because I see it in the HTML code generated by the browser.
Anyway, I tried the following code to debug
function myFunc(variable) { var x = variable; var y = 'This-is-the-real-id' alert(x + ', ' + y) var s = document.getElementById(x); s.value = 'New value' } When the alert message shows up, both parameters are the same, but I still get the error. But everything works fine when I do
var s = document.getElementById('This-is-the-real-id'); s.value = 'New value' How can I fix this?
The element for which I am setting the value is a hidden field and the id is set dynamically, as the page loads. I have tried added this in the $(document).ready function, but it did not work.
alert()orconsole.log()in cases like this, you should always wrap values with some marker characters so you can tell whether there are stray space characters in the strings. So:alert("[" + x + "], [" + y + "]");