Home > Enterprise >  How to get Value of Input Field to Update button color in EJS
How to get Value of Input Field to Update button color in EJS

Time:08-28

I have a form field in EJS and I want the color of the button to change when the input value change.

<div>
        <textarea name="mytextarea" id="inputcontent" cols="30" rows="3" style="margin-top: 10px; margin-bottom: 10px; font-size: 18px; font-weight: 400; width: 100%; border: 0px; opacity: 30%;" placeholder="Share your typology reasoning by commenting here"></textarea>
      </div>
      <div>
        <p >
          
            <% if (document.getElementById('inputcontent').value != '') { %>
          <button type=""   id="submitComment" onclick="addComment()" <i  aria-hidden="true" id="sendlogo">send</i></button>
          <% } else { %>
          <button type=""   id="submitComment" onclick="addComment()" <i  aria-hidden="true" id="sendlogo">send</i></button>
          <% } %>
        </p>
      </div>

My code is throwing error:

 >> 95|             <% if (document.getElementById('inputcontent').value != '') { %>

    96|           <button type=""   id="submitComment" onclick="addComment()" <i  aria-hidden="true" id="sendlogo">send</i></button>

    97|           <% } else { %>

    98|           <button type=""   id="submitComment" onclick="addComment()" <i  aria-hidden="true" id="sendlogo">send</i></button>


document is not defined
    at eval ("C:\\Users\\*********\\views\\partials\\comment_area.ejs":12:8)

CodePudding user response:

You can't use document inside your ejs tags since that code is executed on the server. Instead you should add a script tag which will run as soon as the page is actually loaded in the browser.

Also, the code you've written will only get executed on first page load and a subsequent input change won't affect the button color. You should add oninput event to the textarea tag and write a function to handle the input change.

The textInputHandler function inside the script tag would look like this:

<script>
  function textInputHandler() {
    var node = document.getElementById('inputcontent');
    if(node.value == '') {
      document.getElementById('submitComment').classList.remove('send-color');
      document.getElementById('submitComment').classList.add('unsend-color');
    }
    else {
      document.getElementById('submitComment').classList.remove('unsend-color');
      document.getElementById('submitComment').classList.add('send-color');
    }
  }
</script>
  • Related