简体   繁体   English

Javascript 通过 Id 获取元素并设置值

[英]Javascript Get Element by Id and set the value

I have a javascript function to which I pass a parameter.我有一个 javascript function ,我向其传递了一个参数。 The parameter represents the id of an element (a hidden field) in my web page.该参数表示我的 web 页面中一个元素(隐藏字段)的 id。 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.当我这样做时,我收到一个无法设置值的错误,因为 object 是 null。 But I know the object is not null because I see it in the html code generated by the browser.但我知道 object 不是 null 因为我在浏览器生成的 html 代码中看到了它。 Anyways, 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 please请问我该如何解决这个问题

EDIT编辑

The element for which I am setting the value is hidden field and the id is det dynamically, as the page loads.我为其设置值的元素是隐藏字段,并且在页面加载时动态检测 id。 I have tried added this in the $(document).ready function but did not work我已经尝试在 $(document).ready function 中添加这个但没有用

If myFunc(variable) is executed before textarea is rendered to page, you will get the null exception error.如果在将 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 

So, make sure your textarea does exist in the page, and then call myFunc, you can use window.onload or $(document).ready function.因此,请确保您的 textarea 确实存在于页面中,然后调用 myFunc,您可以使用 window.onload 或 $(document).ready 函数。 Hope it's helpful.希望它有帮助。

Given给定的

<div id="This-is-the-real-id"></div>

then然后

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");
}

will do what you want会做你想做的


Given给定的

<input id="This-is-the-real-id" type="text" value="">

then然后

function setValue(id,newvalue) {
  var s= document.getElementById(id);
  s.value = newvalue;
}    
window.onload=function() {
  setValue("This-is-the-real-id","Hello there");
}

will do what you want会做你想做的

 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 updateTextarea(element)
{
document.getElementById(element).innerText = document.getElementById("ment").value;
}
</script>
</head>
<body>

<input type="text" value="Enter your text here." id = "ment" style = " border: 1px solid grey; margin-bottom: 4px;"  

onKeyUp="updateTextarea('myDiv')" />

<br>

<textarea id="myDiv" ></textarea>

</body>
</html>

For each element type, you can use specific attribute to set value.对于每种元素类型,您可以使用特定的属性来设置值。 Eg:例如:

<div id="theValue1"></div>
window.document.getElementById("theValue1").innerText = "value div";

<input id="theValue2"></input>
window.document.getElementById("theValue2").value = "value input";

You can try example here!您可以在此处尝试示例!

Coming across this question, no answer brought up the possibility of using .setAttribute() in addition to .value()遇到这个问题,除了.value()之外,没有答案提出使用.setAttribute()的可能性

document.getElementById('some-input').value="1337";
document.getElementById('some-input').setAttribute("value", "1337");

Though unlikely helpful for the original questioner, this addendum actually changes the content of the value in the pages source, which in turn makes the value update form.reset() -proof.尽管对原始提问者不太可能有帮助,但此附录实际上更改了页面源中值的内容,从而使值更新form.reset() -proof。

I hope this may help others.我希望这可以帮助其他人。

(Or me in half a year when I've forgotten about js quirks...) (或者半年之后我忘记了js的怪癖……)

try like below it will work...像下面这样尝试它会起作用......

<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>

I think the problem is the way you call your javascript function.我认为问题在于您调用 javascript 函数的方式。 Your code is like so:你的代码是这样的:

<input type="button" onclick="javascript: myFunc(myID)" value="button"/>

myID should be wrapped in quotes. myID 应该用引号括起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM