conditional statement is not working in ejs - node.js

Hello I wants to apply conditional statement in ejs but it is not working in my code "i wants that when i select the a specific value(not using transportation) then buton shows otherwise not show but its showing only - (else condition) on every selection from dropdown" in developer tools it is showing the conditional statement code like this https://ibb.co/60ZWcXh that it is not taking
conditional statement
<%if (locals.students == "noTransportation") { %>
<button type="button" class="btn btn-primary pull-right" onclick="" id="">
Migrate to Applicants
</button>
<%} else { %>
-
<% } %>
complete students_list.ejs
<select class="form-control changeDropDown" id="transportation">
<option value="applications">Applications</option>
<option value="transportation">Using Transportation</option>
<option value="noTransportation">Not Using Transportation</option>
<option value="All">All</option>
</select>
<%if (locals.students == "noTransportation") { %>
<button type="button" class="btn btn-primary pull-right" onclick="" id="">
Migrate to Applicants
</button>
<%} else { %>
-
<% } %>
controller:
in controller the code in comments ////data migration code//// is for this conditional statement but its not working
paste.ofcode.org/RGu9t7Fm3uNPNKiczNP2p9
how can I resolve this issue

If you put a console.log(locals.students) right above the if condition, you'll see (in your node's terminal) that locals.students has a value that's different than noTransportation. Add it like this:
<select class="form-control changeDropDown" id="transportation">
<option value="applications">Applications</option>
<option value="transportation">Using Transportation</option>
<option value="noTransportation">Not Using Transportation</option>
<option value="All">All</option>
</select>
<% console.log("====================", locals.students) %>
<%if (locals.students == "noTransportation") { %>
<button type="button" class="btn btn-primary pull-right" onclick="" id="">
Migrate to Applicants
</button>
<%} else { %>
-
<% } %>
If you want to see that the if actually works properly, you can put, temporarily, instead of the console.log(....):
<% locals.students = "noTransportation" %>
Update:
There's no quick & easy solution that could fit in an answer on stackoverflow for what you currently have.
Some ideas for you to follow:
the code inside <% .. %> is executed on the server.
the selection change of the select box is executed in the browser
in order to have the button show whenever a change is made, you can:
add a client side js function to hide/show the button whenever $("#transportation") changes - but this alone will save nothing in your DB
make a server request and redraw the whole page when $("#transportation") changes, so that your ejs can be executed.

Related

req.body option selected express ejs

Hi would like to send the selected option in dropdown menu, to show only the products from my mongodb.
If i use a submit button, works, but i would like to do without button. some help?
app.post('/windproducts', async (req, res) =>{
let tipoProducto = req.body.tipo_producto;
console.log(tipoProducto)
const windproducts = await WindProduct.find({"tipo_producto": {$eq:tipoProducto}})
res.redirect('windproducts/tablas', {windproducts})
}
)
in EJS:
<form action="/windproducts" method="POST">
<select id="productosTipo" class="validated-form" name="tipo_producto">
<option name="" value="">Todo</option>
<option name="tabla" value="tabla">Tabla</option>
<option name="vela" value="vela">Vela</option>
</select>
<!-- <button class="btn btn-success">mostrar</button> -->
</form>
Thanks
<% %>
use this syntax in your view file to use foreach loop on object
<%
Object.keys(obj).forEach(function(key) {
%>
// HTML Code
<%
});
%>

node js delete go to wrong route

I have app. I added DELETE feature by id. It looks like:
router.delete('/delete/:id', async function (req, res){
console.log("I'm here..");
try {
var id = req.params.id;
console.log("here!!!");
console.log(id);
var x = await Order.findByIdAndDelete(id).exec();
await x.save();
console.log("deleted!");
}catch (exc){console.log("Error during deleting!")}
res.redirect('back');
});
I have also form on my view (i use EJS).
<h1 class="mt-4">Dashboard</h1>
<p class="lead mb-3">Witaj <%= user.name %></p>
<% include ('./partials/messages.ejs')%>
<div class="row mt-5 float-left">
Wszystkie zamówienia
<table class="table float-left">
<tbody>
<% orders.forEach(function(value) { %>
<tr>
<form method="PATCH" action="/orders/order/<%=value.id%>">
<td>Id zamówienia <%= value.id %></td>
<td>Id klienta <%= value.userID %></td>
<td><input type="datetime-local" value= <%= value.dateStart %>
min=<%= value.dateStart %> max=<%= value.dateFinish %>> data rozpoczęcia</td>
<td><input type="datetime-local" value= <%= value.dateFinish %>
min=<%= value.dateStart %> max=<%= value.dateFinish %> >data zakończenia</td>
<td>Cena: <%= value.total %></td>
<td>Ilość dni <%= value.numberOfDays %></td>
<td> <button type="submit" class="btn btn-primary btn-lg">Edytuj i akceptuj</button></td>
</form>
**THERE IS A BUTTON** <form method="DELETE" action="/orders/delete/<%=value.id%>">
<td><button type="submit" class="btn btn-primary btn-lg" value="delete">Usuń</button></td></form>
<form method="POST" action="/orders/confirmOrder/<%=value.id%>">
<td><button type="submit" class="btn btn-primary btn-lg">Akceptuj</button></td></form>
</tr>
<% }) %>
</tbody>
</table>
</div>
Everything looks ok, and should work but it doesn't! Http request looks ok:
GET /orders/delete/607d4b8b06e1aee2dfa901be? 404 84.803 ms - 2580 - but WebStorm shows GET in console. Quite strange. Why? It should shows DELETE. Id of order is okay - taken from database.
Console.logs from route like "here!!!", "I'm here.." aren't showed by console. So I think something is wrong with route.
Moreover after action my layout stopping work because "user is not defined" - yes, i check if user is logged in the layout. It indicates that something is wrong - I have the same situation with other action, but I fixed it. Here I spent 4hrs at night and haven't fixed it yet.
Please, show me what is wrong here.
Kind Regards!
Problem solved! HTML <form> doesn't support DELETE! I was forced to use jquery to send delete request, or to change delete to post in route and in the view.
Now my view and route look:
<td><button type="submit" id="del-button" class="btn btn-primary btn-lg " value=<%=value.id%>>Usuń</button></td></form>
and route:
router.post('/delete/:id', async function (req, res){
//body here
});
I left my answer. Maybe someone use it in the future.

Retrieving value from input in EJS with NodeJS

Here is my EJS code:
<form action="/" method="POST">
<% items.forEach((item)=>{ %>
<div class="item">
<input type="checkbox" name="checkbox" value="<%=item._id%>" onchange="this.form.submit()">
<p><%= item.name %></p>
</div>
<% }) %>
</form>
And here is the app.js:
app.post('/',(req,res)=>{
console.log(req.body.checkbox);
})
My questions are:
1) Why does it only log the value of the selected checkbox (assumed that there are 3 items) instead of 3 values, is it because of the post method only post the checkbox's value that has the property checked == true?
2) If I add another checkbox like below, why does it return undefined if I try to console.log(req.body.item_id)?
<form action="/" method="POST">
<% items.forEach((item)=>{ %>
<div class="item">
<input type="checkbox" name="checkbox" value="<%=item._id%>" onchange="this.form.submit()">
<p><%= item.name %></p>
<input type="checkbox" name="item_id" value="<%=item._id%>">
</div>
<% }) %>
</form>
3) I've tried to do the same thing above but this time it is using input type of text. Why does the console.log(req.body.item_id) show 3 values instead of 1 (which corresponds with the selected checkbox like in question 1)?
<form action="/" method="POST">
<% items.forEach((item)=>{ %>
<div class="item">
<input type="checkbox" name="checkbox" value="<%=item._id%>" onchange="this.form.submit()">
<p><%= item.name %></p>
<input name="item_id" value="<%=item._id%>">
</div>
<% }) %>
</form>
All response are appreciated. Thank you!
That is the default behaviour of the checkbox, it only gets
passed as data if its checked, if it doesn't get passed, we can
assume it wasn't checked
However if you still want the checkbox in data even if it was not checked, one hack would be
Create a hidden element with same name as your checkbox & set value as 'off'
Before submit, if the checkbox is checked, disable the hidden input element
this will give your checkbox value 'on' when checked & 'off' when its not
As mentioned above, it will only added to formdata if its
checked, when its not checked, the element is not added to formdata
at all, so you will get undefined if its not checked
Again this is default behaviour of input types, the reason it
does not do same for checkbox is because, maybe you are only
selecting 1 checkbox with same name before submit, if you do select
multiple checkbox with same name in checkboxes, you'll get same
result for checkboxes too, but due to the reason mentioned in first
answer, it only get's us the element selected which is 1 in your
case

NodeJS send to POST also unchecked input

I have a form in which I iterate an input checkbox field n times, as follows:
<form class="" action="" method="post">
<% availableDirezione.forEach((direzione, index) => { %>
<p>
<input class="checkbox" type="checkbox" name="checkArray" id="check0" value="1">
<span><%= direzione.usr_udf_direzione %> (<%= direzione.usr_udf_dirid %>) </span>
</p>
<% }) %>
<button type="submit" class="btn btn-primary float-right mb-5">Add Mapping</button><br>
</form>
I would like that in the post method, even the unchecked values are passed in the checkArray object.
Let's suppose the forEach iterates 5 times, and only the first and last checkbox are checked, I would like that the checkArray object is as following:
...
body : {
checkArray : [1,0,0,0,1]
}
...
I tried adding the hidden checkbox with a 0 value. It fills the checkArray object 5 times but in wrong error. Any tips?
Sorry but is not possible. This is not due to a Node.js limitation but rather a HTML standard. See second 'note' block in
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox (under value section)
Hence you may try to fight against it with some front-end js code, but I wont suggest it. What you need to do is have a mean to reconstruct the array at the end like this:
<form class="" action="" method="post">
<% availableDirezione.forEach((direzione, index) => { %>
<p>
<input class="checkbox" type="checkbox" name="checkArray" id="check0" value="<%= index %>">
<span><%= direzione.usr_udf_direzione %> (<%= direzione.usr_udf_dirid %>) </span>
</p>
<% }) %>
<button type="submit" class="btn btn-primary float-right mb-5">Add Mapping</button><br>
</form>
Then when you receive your POST:
availableDirezione.map((direzione, index) => checkArray.indexOf(index) !== -1 0 : 1)
This will produce a [0, 1, 1, 0, 0 ... ] array
availableDirezione.map((direzione, index) => checkArray.indexOf(index) !== -1 direzione : none)
Were this will produce a [none, {direzione}, {direzione}, ... ] array
The trick is to use value as your value media and set there something adequate. In this case i used the index of the value inside availableDirezione array, but you may even put set it to something even more meaningful like a unique id present in your direzione objects.

Format messages for javascript form evaluation

I have been trying to develop a simple extension for Safari Firefox and Chrome in wich a form is presented to a user on a pop-up and after being filled out is locally evaluated and the response to the user is defined on that evaluation.
The original form can be found on: https://dl.dropbox.com/u/86545493/Waze/Calculadora.html
I have also already been able to create a working safari extension that can be downloaded here: https://dl.dropbox.com/u/86545493/Waze/Extensions/WRTC.safariextz
but my problems starte when trying to create the chrome extension.
I followed the tutorial for creating a first extension and was able to create a button and load the form as a popup. However the security restrictions do not allow my form to run. From what I have understood by reading the Developers Guide what I need is to separate the javascript in its own file and call it from the popup file. However the language of the documents is too technical for me (med student) and I have been unable to understand the proper way to format the messages that should be used. Here is the current status for my code:
popup.html
<head>
<script type="text/javascript" src="popup.js"></script>
</head>
<body>
<h1>Calculadora de Tipo de Camino</h1>
<form id="Calle" target="_self">
Cruceros <select id="cruceros">
<option value=1>Glorietas</option>
<option value=1>Rotondas</option>
<option value=1>Sem&aacuteforos</option>
<option value=0 selected>Sin Control</option>
<option value=2>Sin Cruceros</option>
</select></br>
Carriles <select id="carriles">
<option value=1 selected>1</option>
<option value=2>2</option>
<option value=3>3 o m&aacutes</option>
</select></br>
Sentidos Separados f&iacutesicamente o parte de par vial <input type="checkbox" id="sentidos"></br>
Con Laterales o Acotamiento <input type="checkbox" id="laterales"></br>
Entradas y Salidas delimitadas <input type="checkbox" id="ramps"></br>
Avenida, Boulevard, o Circuito <input type="checkbox" id="name"></br>
Es Carretera
<select id="carretera">
<option value=0 selected>No</option>
<option value=1>Municipal</option>
<option value=2>Estatal</option>
<option value=3>Federal</option>
</select> Revisar en: SCT</br>
Tiene topes <input type="checkbox" id="topes"></br>
</br>
</form>
<button type="button" onclick="textR()">Calcular Puntos</button>
<hr><p id="resultn"></p>
<p id="resultt"></p>
</body>
popup.js
function textR()
{var cru=document.getElementById("cruceros").value;
if (cru==0){crun=0}
else if (cru==1){crun=1}
else{crun=2}
var carr=document.getElementById("carriles").value;
if (carr==1){carrn=0}
else if (carr==2){carrn=1}
else{carrn=2}
sen=(document.getElementById("sentidos").checked==true)?1:0;
lat=(document.getElementById("laterales").checked==true)?1:0;
ram=(document.getElementById("ramps").checked==true)?1:0;
av=(document.getElementById("name").checked==true)?1:0;
var hw=document.getElementById("carretera").value;
if (hw==1){hwn=1}
else if (hw==2){hwn=2}
else if (hw==3){hwn=3}
else{hwn=0}
saluden=(document.getElementById("topes").checked==true)?1:0;
var r=crun+carrn+sen+lat+ram+av+hwn+saluden;
document.getElementById("resultn").innerHTML=(r+" puntos");
if (r<2){rt='Street'}
else if (r<4){rt='<span class="pstreet">Primary Street'}
else if (r<7){rt='<span class="mihw"> Minor Highway '}
else if (r<9){rt='<span class="mahw"> Major Highway '}
else {rt='<span class="fw"> Freeway '}
document.getElementById("resultt").innerHTML=(rt);
}
Could you please tell me the proper syntax to be used?
Eliminate Inline code onclick="textR()" and add it in popup.js as shown here
document.getElementsByTagName("button")[0].addEventListener("click",textR);
In the end I ended up putting document.getElementById("calcButton").addEventListener("click", textR); at the end of popup.js and had to move <script type="text/javascript" src="popup.js"></script> to the end of the popup.html.
I found this article usefull: Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Resources