简体   繁体   中英

How to create a clone of Search field?

I have a search field in my app. I need to clone this search field with the same functions. One search field at the left side of the page and another, the same search field, at the right side of the page.

How I can make the clone using JS?

Below my JS code

document.querySelector('#city').addEventListener(click,'keyup', function(e) {
  if (e.keyCode === 13) {

        var city = $(this).val();
        if (city !== '') {

            $.ajax({

                url: 'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" +
                    "&APPID=bb037310921af67f24ba53f2bad48b1d",
                type: "GET",
                dataType: "json",
                success: function (data) {
                    var widget = show(data);

                    $("#show").html(widget);

                    $("#city").val(' ');

                }

            });

        } else {
            $("#error").html("<div class='alert alert-danger text-center'><a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a>Field cannot be empty</div>");
        }

    };
});


function show(data) {
    return "<h2>Current Weather for " + data.name + "," + data.sys.country + "</h2>" +
    "<h3><strong>Wind Speed</strong>: " + data.dt + "</h3>" +
        "<h3><strong>Weather</strong>: <img src='http://openweathermap.org/img/w/" + data.weather[0].icon + ".png'>" + data.weather[0].main + "</h3>" +
        "<h3><strong>Description</strong>: " + data.weather[0].description + "</h3>" +
        "<h3><strong>Temperature</strong>: " + data.main.temp + "&deg;C</h3>" +
        "<h3><strong>Wind Direction</strong>: " + data.wind.deg + "&deg;</h3>";

}

and part of HTML code

<body>
    <div class="jumbotron" id="jumbo">
        <h2 class="text-center" id="th2">Weather</h2>
    </div>

    <div class="container" id="cont">
        <div class="row">
            <h2 class="text-center text-primary">Your City</h2>
            <span id="error"></span>
        </div>

        <div class="row form-group form-inline" id="rowDiv">
            <input type="text" name="city" id="city" class="form-control" placeholder="City Name">
            <button id="submitWeather" class="btn btn-primary">Search City</button>
        </div>

        <div id="show"></div>

        </div>

As an option, I would suggest to create some function or class that creates input and description nodes and append to whatever container id (or class) you pass to it. In html you would only need element with rowDiv id. Obviously you can tailor it to your needs, but it's just an idea. I thought something like this:

// rough example based of your code
class citySearch {
    constructor(parentContainerId) {
        this.searchField;
        this.displayArea;
        this.setStage(parentContainerId);
        this.hookListener();
    }

    setStage(parentContainerId) {
        this.searchField = document.createElement('input');
        this.displayArea = document.createElement('div');
        var parentContainer = document.getElementById(parentContainerId)

        parentContainer.appendChild(this.searchField);
        parentContainer.appendChild(this.displayArea);
    }

    show(data) {
        return "<h2>Current Weather for " + data.name + "," + data.sys.country + "</h2>" +
            "<h3><strong>Wind Speed</strong>: " + data.dt + "</h3>" +
            "<h3><strong>Weather</strong>: <img src='http://openweathermap.org/img/w/" + data.weather[0].icon + ".png'>" + data.weather[0].main + "</h3>" +
            "<h3><strong>Description</strong>: " + data.weather[0].description + "</h3>" +
            "<h3><strong>Temperature</strong>: " + data.main.temp + "&deg;C</h3>" +
            "<h3><strong>Wind Direction</strong>: " + data.wind.deg + "&deg;</h3>";

    }

    hookListener() {
        this.searchField.addEventListener('keypress', this.onClick.bind(this));
    }

    onClick(e) {
        if (e.keyCode === 13) {
            var city = this.searchField.value;
            if (city !== '') {
                fetch('http://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" + "&APPID=bb037310921af67f24ba53f2bad48b1d")
                .then( async(res) => {
                    const data = await res.json();
                    var widget = this.show(data);
                    this.displayArea.innerHTML = widget;
                    this.searchField.value = '';
                })

            } else {
            this.displayArea.innerHTML = "<div class='alert alert-danger text-center'><a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a>Field cannot be empty</div>";
            }
        }
    }
}
var firstSearch = new citySearch('rowDiv');
var secondSearch = new citySearch('rowDiv');

Html

 <div class="row form-group form-inline" id="rowDiv"></div>

Here is some sample code that allows 1 code base, 2 search boxes and keeps the two search boxes in sync.

 const searchBoxes = () => document.getElementsByClassName('searchbox'); document.addEventListener('DOMContentLoaded', function() { Array.from(searchBoxes()).forEach(element => { console.log(element.id); element.addEventListener('keyup', function(event) { let text = event.target.value; // This is just a demo document.getElementById("searchResult").innerHTML = text; // Loop other search boxes Array.from(searchBoxes()).forEach(e => { if (e.id != event.target.id) e.value = text; }); // ANY CODE HERE TO APPLY SEARCH }); }); }); 
 .searchbox { border: 1px solid black; background-color: wheat; } #searchResult { height: 100px; width: 100px; background-color: yellow; font-weight: bold; } 
 <div> <span>Some Text Here</span> <input id="search1" class="searchbox" type="text" /> </div> <div id="searchResult">ALL MY PAGE STUFF</div> <div> <span>Some Text Here</span> <input id="search2" class="searchbox" type="text" /> </div> 

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