简体   繁体   中英

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. My code (with search.ejs) is as follows:

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

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. 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. Set innerHTML of "mySearch" box to the value of "searchValue" input field. The code - document.getElementById("mySearch").innerHTML = document.getElementById("searchValue").value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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