简体   繁体   中英

Display links in function of what the user entered in a text field

I hope you're all fine. First of all i'm a very very very beginner in web dev so i'm here to ask for your help. I'm not sure if SO is the right place for that type of demand and if not, i want to apologize and feel free to delete my post.
I want to make a text field that display text (a link with an href) in function of what you writed in the text field.

Let me precise. I have a data list of postal code. In function of your postal code, you have proper delivery day. (its an e-commerce website and there is one page for each delivery day) For example, if you live in postal code 69001 (french postal code system), you will enter it in the text field and press enter or on click on a button, it display the correct link regarding the postal code you entered.

I have tried nuemrous things. I can make the text field with the data list but i do not know how to display the correct links in regard of what the user writed in the text field.

I hope i have been clear with my problem and i wish you all an happy day.

If I understand the question correctly, then I've actually done a very similar project myself, when I was trying to figure PostgreSQL out. This is what I did:

Firstly I created an input (notice the oninput="zipChanged()" in the following line of code):

    <input list="zips" name="zips" id="zipCode" oninput="zipChanged()" placeholder="ZIP code">

Then I gave it a list where it'd show 5 possible options using the <datalist> tag as the block to place all of the options in, and the <option> tag to put each of the possible options in.

            <datalist id="zips">
              <option id="zipOption1">
              <option id="zipOption2">
              <option id="zipOption3">
              <option id="zipOption4">
              <option id="zipOption5">
            </datalist>

After this due to the fact that I had oninput="zipChanged" written inside of the input, every time the user wrote in or removed out any number while they were writing their Zip Code in, the function zipChanged() would be activated. The function was like this:

        var currentSearch = document.getElementById("zipCode").value;
        var url = "http://127.0.0.1:8096/?need=" + currentSearch;
        xhttp.open("GET", url, true);

        xhttp.onreadystatechange = function () {
            if (this.readyState == 4) {
                if (this.status == 200) {
                    zipPossibilities_G = JSON.parse(this.responseText);
                    fillZipPossibilities();
                } else { }
            }
        };
        xhttp.send();

Let me break the function down for you:

the following line was used to put the user's written in value in the text input into the variable called currentSearch.

    var currentSearch = document.getElementById("zipCode").value;

The rest of the code was used in order for my HTML file to connect to my nodeJS server which I used to connect to my PostgreSQL database, from which I extracted the Zip Codes in the database most similar to the portion of the Zip Code the user had entered as a way to show to the user possible Zip Codes they might trying to type in. The server was able to do this by finding Zip Codes starting with the same numbers as the portion of the Zip Code entered by the user. It sent an SQL code to the database telling it to give the information, this was the code:

    select "[name of the column in which the Zip Codes are]" from "[name of your table in the databse]" where "[name of the column in which the Zip Codes are]" like '[the number entered by the user]%' limit 5;

and if needed this was the full code of the server (I changed out some variables, added some more comments and such to clarify what was what):

    const http = require('http');
    const url = require('url');
    const { Client } = require('../../../nodeModules/pg/node_modules/pg');

http.createServer(function (req, res) { //creating the http server from which the information can be extracted
    const client = new Client({
    user: "[the PostgreSQL user you're using to manage the database]",
    password: "[password to your database]",
    host: "localhost",
    port: 5432,
    database: "[the name of your database]"
});
res.writeHead(200, { 'Content-Type': 'text/html' });
res.writeHead(200, { "Access-Control-Allow-Origin": "*" });
try {
    execIt();
    async function execIt() { //creating an async function, it is important as otherwise await won't work
        try {
            var infoFromURL = url.parse(req.url, true).query; // 
            console.log("the Num: " + infoFromURL.need);
            var neededNum1 = infoFromURL.need;
            var neededNum = neededNum1.toString();
            if ((neededNum.length > 5) || (neededNum.length == 5)) {
                res.write("");
                return res.end();
            } else {
                await client.connect(); //waits for the client to connect
                console.log("Connected successfully.");
                // the following line has the SQL code that'll be sent to the database
                const { rows } = await client.query("select \"[name of the column in which the Zip Codes are]\" from \"[name of your table in the databse]\" where \"[name of the column in which the Zip Codes are]\" like \'[the number entered by the user]%\' limit 5;");
                console.log(rows);
                // from here to up till "return res.end();" line the entire code is just to print out the data recovered from the database
                var toPrint = "[";
                for (var i = 0; i < 5; i++) {
                    if (i == 4) {
                        toPrint = toPrint + "\"" + rows[i].zip.toString() + "\"" + "]";
                    } else {
                        toPrint = toPrint + "\"" + rows[i].zip.toString() + "\"" + ", ";
                    }
                }
                console.log(toPrint);
                res.write(toPrint);
                await client.end();
                console.log("Client disconnected successfully.");
                return res.end();
            }
        } catch (ex) {
            console.log(`Something wrong happend ${ex}`);
        }
    }
} catch (error) {
    console.log(error);
}

}).listen(8096); console.log('Server running at http://127.0.0.1:8096/' );

Since you're probably not using PostgreSQL and maybe even not nodeJS you could ignore the code above, but if you are it could help.

This basically sent the first 5 Zip Codes with the most similar beginnings to the portion of the Zip Code entered by the user.

The following part of the zipChanged() function was to collect the sent back information and sort it.

                    zipPossibilities_G = JSON.parse(this.responseText);
                    fillZipPossibilities();

here the array zipPossibilities_G (which is a global array) collects the text sent back by the nodeJS server to the html file, and the function fillZipPossibilities() is the fill the options in.

fillZipPossibilities() was like this:

            function fillZipPossibilities() {
               for (var i = 0; i < 5; i++) {
                  document.getElementById(zipOptionArr_G[i]).value = 
                  zipPossibilities_G[i];
               }
            }

here each of the 5 <option> tags get's filled with the sent back files. The zipOptionArr_G array is another global array which has the ids of the 5 <option> tags and looks like this

  var zipOptionArr_G = ["zipOption1", "zipOption2", "zipOption3", "zipOption4", "zipOption5"];

I hope I understood the question right and that this helped you out

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