Mám javascriptovú funkciu, ktorej odovzdávam parameter. Parameter predstavuje id prvku (skryté pole) na mojej webovej stránke. Chcem zmeniť hodnotu tohto prvku.
function myFunc(variable){
var s= document.getElementById(variable);
s.value = 'New value'
}
Keď to urobím, zobrazí sa chyba, že hodnotu nemožno nastaviť, pretože objekt je nulový. Viem však, že objekt nie je nulový, pretože ho vidím v html kóde vygenerovanom prehliadačom. Každopádne som vyskúšal nasledujúci kód na ladenie
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'
}
Keď sa zobrazí výstražná správa, oba parametre sú rovnaké, ale stále sa mi zobrazuje chyba. Všetko však funguje správne, keď urobím
var s= document.getElementById('This-is-the-real-id');
s.value = 'New value'
Ako to môžem opraviť, prosím
EDIT
Prvok, pre ktorý nastavujem hodnotu, je skryté pole a id sa určuje dynamicky pri načítaní stránky. Skúšal som to pridať do funkcie $(document).ready, ale nefungovalo to
Ak sa myFunc(premenná) vykoná pred vykreslením textového priestoru na stránku, dostanete chybu null exception.
<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
Takže sa uistite, že váš textarea na stránke existuje, a potom zavolajte myFunc, môžete použiť funkciu window.onload alebo $(document).ready. Dúfam, že je to užitočné.
Vzhľadom na
<div id="This-is-the-real-id"></div>
potom
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");
}
urobí to, čo chcete
Dané
<input id="This-is-the-real-id" type="text" value="">
potom
function setValue(id,newvalue) {
var s= document.getElementById(id);
s.value = newvalue;
}
window.onload=function() {
setValue("This-is-the-real-id","Hello there");
}
urobí to, čo chcete
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="">
skúste to ako nižšie, bude to fungovať...
<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>