i am following the odin project, in the node lesson they use Jade but i am using Ejs for the template language. I have the following code:
<%- include ./partials/startBody.ejs %>
<div class="col-sm-10">
<h1><%= title %></h1>
<form method="POST" action="">
<div class="form-group">
<label for="name">Genre:</label>
<input id="name" class="form-control" type="text" placeholder="Fantasy, Poetry etc." name="name" value="<%= genre.name %> "/>
</div>
<button class="btn btn-primary" type="submit">Submit</button>
</form>
<% if (typeof errors !== "undefined") { %>
<ul>
<% for (var error of errors) { %>
<li><%= error.msg %></li>
<% } %>
</ul>
<% } %>
<%- include ./partials/endBody.ejs %>
This route needs to handle the form when the user input incomplete data so it has to return the data typed, i have the problem where when first rendering the view the input with the name id has no value because there is no genre defined,
<input id="name" class="form-control" type="text" placeholder="Fantasy, Poetry etc." name="name" value="<%= genre.name %> "/>
I tried also the following:
<input id="name" class="form-control" type="text" placeholder="Fantasy, Poetry etc." name="name" value="<%= if (typeof genre.name !== "undefined") {genre.name}%> "/>
But then it not recognizes the if, How can i handle this?
Thanks a lot!
You can use a ternary operator to check if genre exists before trying to access its name property. Here's an example:
This code checks if genre exists and has a name property. If so, it sets the input's value to genre.name. Otherwise, it sets the value to an empty string. This way, the input will have a default value of an empty string if genre is not defined.
The ternary operator condition ? valueIfTrue : valueIfFalse is a shorthand way to write an if statement. In this case, the condition is (genre && genre.name), which checks if genre exists and has a name property. If this is true, the value of the input is set to genre.name. If not, it's set to an empty string.