パラメータを渡すjavascriptの関数があります。このパラメータは、Webページ内の要素(隠しフィールド)のIDを表しています。この要素の値を変更したいと思います。
function myFunc(variable){
var s= document.getElementById(variable);
s.value = 'New value'
}
これを実行すると、「オブジェクトがnullなので値を設定できない」というエラーが発生します。しかし、ブラウザで生成されたHTMLコードを見ると、オブジェクトはnullではないことがわかります。 とにかく、デバッグのために次のコードを試してみました。
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'
}
アラートメッセージが表示されたとき、両方のパラメータは同じですが、やはりエラーが発生します。しかし、次のようにするとすべてうまくいきます。
var s= document.getElementById('This-is-the-real-id');
s.value = 'New value'
どうすれば解決できますか?
EDIT
値を設定しようとしている要素はhiddenフィールドで、idはページの読み込み時に動的に決定されます。これを$(document).ready関数に追加しようとしましたが、うまくいきませんでした。
textareaがページにレンダリングされる前にmyFunc(variable)を実行すると、null例外エラーが発生します。
<html>
<head>
<title>index</title>
<script type="text/javascript">
function myFunc(variable){
var s = document.getElementById(variable);
s.value = "new value";
}
myFunc("id1");
</script>
</head>
<body>
<textarea id="id1"></textarea>
</body>
</html>
//Error message: Cannot set property 'value' of null
そこで、textareaがページ内に存在していることを確認してからmyFuncを呼び出すようにしてください。 ご参考になれば幸いです。
与えられた
<div id="This-is-the-real-id"></div>
とすると
function setText(id,newvalue) {
var s= document.getElementById(id);
s.innerHTML = newvalue;
}
window.onload=function() { // or window.addEventListener("load",function() {
setText("This-is-the-real-id","Hello there");
}
はあなたが望むことをします。
与えられた
<input id="This-is-the-real-id" type="text" value="">
とすると
function setValue(id,newvalue) {
var s= document.getElementById(id);
s.value = newvalue;
}
window.onload=function() {
setValue("This-is-the-real-id","Hello there");
}
はあなたが望むことをします。
function setContent(id, newvalue) {
var s = document.getElementById(id);
if (s.tagName.toUpperCase()==="INPUT") s.value = newvalue;
else s.innerHTML = newvalue;
}
window.addEventListener("load", function() {
setContent("This-is-the-real-id-div", "Hello there");
setContent("This-is-the-real-id-input", "Hello there");
})
<div id="This-is-the-real-id-div"></div>
<input id="This-is-the-real-id-input" type="text" value="">
以下のようにしてみると、うまくいくと思います。
<html>
<head>
<script>
function displayResult(element)
{
document.getElementById(element).value = 'hi';
}
</script>
</head>
<body>
<textarea id="myTextarea" cols="20">
BYE
</textarea>
<br>
<button type="button" onclick="displayResult('myTextarea')">Change</button>
</body>
</html>