1

I'm building an application that will allow users to click on a button and when they return to the page, it will show a message saying "Already interested". When I display the page, it skips over the if statement in the for loop and displays the else statement. What am I doing wrong?

Below is my code and current output.

<% for(var i=0; i < userInterests.length; i++) { %>
   <% if ((username == userInterests[i].username)  && (postID == userInterests[i].post_id)){ %> 
      <p>Already interested</p>
      <% break; %> 
   <% } else { %> 
      <form action="/jobs/interested/<%= post._id %>" method='POST'>
         <button type="submit" class="btn btn-info">I'm interested</button>
      </form>
      <% break; %> 
   <% } %> 
<% } %>

current output

MongoDB entry

3
  • It does not like an issue with EJS. Otherwise, it would not have compiled. Try to log all the values in the if statement and see their values in the loop. That will give you a clear idea of why your if statement is evaluated as false. Commented Dec 6, 2020 at 19:33
  • For your logic to be more solid in js, consider using === instead of ==. Commented Dec 6, 2020 at 19:35
  • I already logged their values and they match the entry in the database. Is there a problem with my code's logic? Commented Dec 6, 2020 at 19:42

1 Answer 1

2

Logic issue , you are testing username and postID only with values of userInterests[0].username and serInterests[0].post_id because you have break; statement in your 2 conditions , Here is a solution for the issue :

<% var userInterested = false %> 
<% for(var i=0; i < userInterests.length; i++) { %>
   <% if ((username == userInterests[i].username)  && (postID == userInterests[i].post_id)){ %> 
          <% userInterested = true; %>
          <% break; %> 
   <% } %>
<% } %>
<% if (userInterested) { %> 
   <p>Already interested</p>
<% } else { %> 
   <form action="/jobs/interested/<%= post._id %>" method='POST'>
      <button type="submit" class="btn btn-info">I'm interested</button>
   </form>
<% } %>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.