简体   繁体   English

传递JavaScript变量以填充innerHTML

[英]Passing a JavaScript variable to fill innerHTML

I'm trying to pass a simple variable from a form input to populate a span with the .innerHTML syntax. 我正在尝试从表单输入中传递一个简单变量,以.innerHTML语法填充跨度。 My code (with search.ejs) is as follows: 我的代码(带有search.ejs)如下:

<script>function readSearchValue() {
      var passedSearchValue = document.getElementById('searchForm').submit();
      document.getElementById('mySearch').innerHTML = passedSearchValue;
    }
  </script>

  <!-- Search form -->
  <nav class="navbar navbar-light bg-light">
    <form class="form-inline" id="searchForm">
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" id="searchValue">
      <button class="btn btn-outline-success my-2 my-sm-0 glyphicon glyphicon-search" type="submit" onclick="readSearchValue()"></button>
    </form>
  </nav>

<p>You have searched for:
    <span id="mySearch"></span>
  </p>

I also have a search.js file which doesn't do much ATM: 我也有一个search.js文件,该文件没有太多的ATM:

res.render('search', {
        title: 'Search results',

I get an undefined error with the code above. 我收到上述代码的未定义错误。 Thanks in advance for any help! 在此先感谢您的帮助!

Kelly. 凯利。

You can directly use ejs expression if you are sending value from the server. 如果要从服务器发送值,则可以直接使用ejs表达式。 if you want to work on the local side then you can see the below code. 如果您想在本地工作,则可以看到以下代码。

 function readSearchValue() { document.getElementById('mySearch').innerHTML = document.getElementById('searchValue').value; document.getElementById('searchForm').submit(); } 
 <!-- Search form --> <nav class="navbar navbar-light bg-light"> <form class="form-inline" id="searchForm" method="POST"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="search" id="searchValue"> <button class="btn btn-outline-success my-2 my-sm-0 glyphicon glyphicon-search" type="button" onclick="readSearchValue();">Submit</button> </form> </nav> <p>You have searched for: <span id="mySearch"></span> </p> 

For now, you cannot see value permanent because the form is submitting so the page is reloading. 目前,您看不到永久值,因为表单正在提交,因此页面正在重新加载。

Your code is near complete. 您的代码即将完成。 The only thing you need to change is the 2nd line of "readSearchValue" function. 您唯一需要更改的是“ readSearchValue”函数的第二行。 Set innerHTML of "mySearch" box to the value of "searchValue" input field. 将“ mySearch”框的innerHTML设置为“ searchValue”输入字段的值。 The code - document.getElementById("mySearch").innerHTML = document.getElementById("searchValue").value 代码document.getElementById("mySearch").innerHTML = document.getElementById("searchValue").value

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

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