简体   繁体   中英

How to render to index.ejs if input field is empty?

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> ).

Changing your conditional statement to see if the parameter is defined and not empty should work. Try something like... Going to the url

http://localhost:3000/search?q=testing

and then

http://localhost:3000/search?q=
const url = require('url');
const querystring = require('querystring');
const bodyParser = require('body-parser');
var express = require('express');
var app = express();
const PORT = 3000;


// about page
app.get('/:name', function(req, res) {
    var name = req.params.name;
    let parsedUrl = url.parse(req.url);
    let parsedQs = querystring.parse(parsedUrl.query);
    if (name == 'search') {
        if ( typeof parsedQs.q !== 'undefined' && parsedQs.q )
        {
            console.log(`Parameter q is set as ${parsedQs.q}`);
            res.send(`Parameter q is set as ${parsedQs.q}`);
        }
        else
        {
            console.log(`Parameter is not set and redirect`);
            res.redirect('http://localhost:3000/defaultPage');
        }
    }else{
        console.log(`Not looking at search page.`);
        res.send("Defaul Page");
    }

});


app.use(express.static("public"));

app.listen(PORT, err =>{
    err ? 
    console.log("Error in server setup") :
    console.log("Server listening on Port", PORT)
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM