如果输入字段为空,如何渲染到index.ejs?
如果我单击“表单”按钮时,我想渲染到“/”,如果输入字段为空。
单击按钮之后我想要的URL是这样的:http:// localhost:3000
header.ejs
<form action="/search" method="GET">
<button id="submitID" type="submit">//button code</button>
<input id="myInputFieldID" type="search" name="q" placeholder="Search">
</form>
search.js
router.get('/', function(req, res) {
if (req.query.q.length > 0) {
db.query("...query...", function(err,example){
console.log("It contains text!");
res.render('search', { ...some data... });
});
} else {
db.query("...query...",function(err,example){
console.log("It's empty!");
res.render('index', { ...some data... });
});
}
});
我在做什么,如果输入包含文本,并且是否为空渲染,则呈现为search.ejs
。问题是,当我渲染到索引时,我会得到这个URL:http:// localhost:3000/search?q =
我尝试删除该网址的那部分,但它不起作用。不过,这是最有效的方法吗?
我应该禁用按钮,直到输入上有文本或实现此目的的最佳方法是什么?
(我不想在&lt; input&gt;
中使用必需
属性)。
I want to render to "/" if the input field is empty when I click the form button.
The URL I want after clicking the button is like this: http://localhost:3000
Header.ejs
<form action="/search" method="GET">
<button id="submitID" type="submit">//button code</button>
<input id="myInputFieldID" type="search" name="q" placeholder="Search">
</form>
search.js
router.get('/', function(req, res) {
if (req.query.q.length > 0) {
db.query("...query...", function(err,example){
console.log("It contains text!");
res.render('search', { ...some data... });
});
} else {
db.query("...query...",function(err,example){
console.log("It's empty!");
res.render('index', { ...some data... });
});
}
});
What I am doing is rendering to search.ejs if the input contains text and if it's empty render to index.ejs
The problem is that when I render to index.ejs I'm gettin this URL: http://localhost:3000/search?q=
I've tried to remove that part of the URL but it didn't work. Still, is this the most efficient way?
Should I disable the button until there is text on the input or what is the best way to achieve this?
(I don't want to use required
attribute inside the <input>
).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
更改条件语句以查看参数是否已定义且不为空应该可行。尝试一些像...
转到网址
,然后
Changing your conditional statement to see if the parameter is defined and not empty should work. Try something like...
Going to the url
and then