JavaScript不会更改输入的html值

时间:2017-03-22 17:51:31

标签: javascript html

    function editcomment(openid) {
      var pageid = "<?= $ID ?>";
      var commentid = "p" + openid;
      console.log(openid);
      console.log(commentid);
      console.log(pageid);
      var commentcontent = document.getElementById(commentid).innerHTML; <-- this is what i want the input to display
      console.log(commentcontent); <-- checking the value proves thats its fine and not blank
      document.getElementById("commenttext").value = commentcontent; <-- this wont change the input just refuses to
      document.getElementById("commenteditid").value = openid;
      document.getElementById("postid").value = pageid;
      document.getElementById("editcommentdiv").style.visibility = "visible";
}

代码将更改输入“postid”但不会更改“commenteditid” 它改变了什么:

<form action="php/edit-comment.php" method="post" autocomplete="off">
<input id="postid" type="hidden" name="idinput" value=""> <-- but these will
<input type="text" id="commenttext" name="commenttext" value=""> <-- this wont change at all 
<input type="hidden" id="commenteditid" name="commenteditid" value=""> <-- but these will
<button id="sendbutton" type="submit"  onclick="preparetext()">Submit</button>
</form>

任何想法如何解决这个问题,因为代码似乎很好,只是值不会改变

2 个答案:

答案 0 :(得分:0)

也许试试这个:

document.getElementById("commenttext").setAttribute('value', commentcontent);

https://jsfiddle.net/dalinhuang/egj31e4g/5

或在这里:

&#13;
&#13;
setTimeout(function() {
  let commentid = 'commentid';
  let commentcontent = document.getElementById(commentid).innerHTML;
  alert(commentcontent);
  document.getElementById("commenttext").setAttribute('value', commentcontent);
}, 2000);
&#13;
<form action="php/edit-comment.php" method="post" autocomplete="off">
  <input id="postid" type="hidden" name="idinput" value="111">
  <!-- but these will -->
  <input type="text" id="commenttext" name="commenttext" value="222">
  <!-- <-- this wont change at all -->
  <input type="text" id="commenteditid" name="commenteditid" value="333">
  <!-- but these will -->
  <!-- <button id="sendbutton" type="submit"  onclick="preparetext()">Submit</button> -->
</form>

<p id='commentid' style="display: none">commentid value</p>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

“ commenttext”是注释文本的ID吗?如果您有多个评论,那不会冲突吗?那很可能就是原因。在第一部分中:您正在做use RealRashid\SweetAlert\Facades\Alert; //etc public function sendEmail(SubmitContactForm $request) { // etc Alert::success('Email Sent', 'We have received your message and would like to thank you for writing to us.'); return redirect()->back(); } ,这是通过其ID找到的特定注释,但是如果所有注释的ID都为“ commenttext”,则getElementById会简单地获取具有该ID的第一个元素。那可能是原因吗?除非您在没有其他评论的单独页面上执行此操作,否则这没有任何意义,因为您是通过将它们的innerHTML检索为评论信息的。