简体   繁体   中英

How to get data from specific event target

I'm trying to extract the name of a street using a click event in my list the entire process of getting the address data is working perfectly using AJAX successful callback I added a successful customer dialog containing the street information he clicked on.

But at the time of the street show in the successful dialogue I wanted to just get the street name and transport it to a input that will be hidden i wish to use the name of that street so that in the future when the client clicks a button copy the address for the form a AJAX that can do a search in my API using the name of this street so that in return of this action return an extended version of that address to my form.

But I can not think or find anything on how to extract just the street name that the client clicked on the list only thing that he can return to me is the original elements generated at the beginning of the list grouping using a route from my API that contains all the registered addresses

I already tried to get the data via the class of the generated elements, but none results.. i am have thought of trying to add an ID to the addresses that were clicked but I could not find anything in the jQuery documentation that could help me.

My elements.js

$(document).ready(function(){
    // Setup Modal
    $('#openSearchAddress').click(function() { 
        // Start Modal
        $('#modalSearchAddress')
           .modal('show')
        ;
    });

    $('#sendSearchAddress').click(function() {
        $.ajax({
            type: "GET",
            dataType: "JSON",
            url: "https://****-api.herokuapp.com/api/itapetininga-street-last-three-searcheds?access_token=7Z****",
            success: function (finalData) {
                // Running test
                console.log(finalData);

                if (finalData) {
                    // var dd = JSON.parse(result);
                    // addressStreet(finalData[0].addressStreet)
                    // name: finalData[0].addressStreet

                    // Print Results
                    var options = {
                        valueNames: ['addressStreet', 'neighborhoodStreet']
                    };

                    // Example One
                    var values = finalData.map(function(finalDatum) {
                        return {
                            addressStreet: finalDatum.addressStreet,
                            neighborhoodStreet: finalDatum.neighborhoodStreet,
                        };
                    });

                    var userList = new List('users', options, values);

                    // Start Selected Address With Event Delegation
                    $("#target_ul").on("click", "li", function(event) {
                        // Prevent Redirect In Click
                        event.preventDefault();

                        // Load Options For Notification
                        var placementFrom = "top";
                        var placementAlign = "center";
                        var colorName = "bg-light-green";

                        // Set Options For Notification
                        showNotification(colorName, null, placementFrom, placementAlign);

                        // Start New Notification
                        function showNotification(colorName, text, placementFrom, placementAlign, animateEnter, animateExit) {
                            if (colorName === null || colorName === '') { colorName = 'bg-black'; }
                            if (text === null || text === '') { text = 'Endereço que você selecionou é '; }
                            if (animateEnter === null || animateEnter === '') { animateEnter = 'animated fadeInDown'; }
                            if (animateExit === null || animateExit === '') { animateExit = 'animated fadeOutUp'; }
                            var allowDismiss = true;
                            // Start Modern Structure For Notification
                            $.notify({
                                message: text
                            }, {
                                type: colorName,
                                allow_dismiss: allowDismiss,
                                newest_on_top: true,
                                timer: 1000,
                                placement: {
                                    from: placementFrom,
                                    align: placementAlign
                                },
                                animate: {
                                    enter: animateEnter,
                                    exit: animateExit
                                },
                                template: '<div data-notify="container" class="bootstrap-notify-container alert alert-dismissible {0} ' + (allowDismiss ? "p-r-35" : "") + '" role="alert">' +
                                    '<button type="button" aria-hidden="true" class="close" data-notify="dismiss">×</button>' +
                                    '<span data-notify="icon"></span> ' +
                                    '<span data-notify="title">{1}</span> ' +
                                    '<span data-notify="message">{2}</span>' +
                                    '<div class="progress" data-notify="progressbar">' +
                                    '<div class="progress-bar progress-bar-{0}" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div>' +
                                    '</div>' +
                                    '<div id="selectedAddress"></div>' +
                                    '<a href="javascript:void(0);" class="alert-link" id="selectedSearchAddress" hidden></a>' +
                                    '<a href="{3}" target="{4}" data-notify="url"></a>' +
                                    '</div>'
                                }
                            );
                        }

                        // Add Selected Address In Notification
                        var selectedAddress = $( this ).text();

                        console.log('Selected address is: ', selectedAddress);

                        if (event.target && event.target.nodeName === 'LI') {
                            let item = event.target;

                            $("#selectedAddress").html(item.innerHTML);
                        }

                        // Prepare Input Hidden For Import Data To Form

                        // Add Informations About Selected Address
                        $('#selectedSearchAddress').text(selectedAddress);
                    });

                    // Print Variable Contain Native Data From All Street In List
                    console.log(values);
                }
            }
        }); 
    });

My list in EJS template

<div id="modalSearchAddress" class="ui small modal" style="margin-bottom: 53px !important;margin-top: 60px !important;margin-left: auto !important;margin-right: auto !important;">
    <div class="content" style="padding: 0rem !important;">
        <div class="row" style="margin-left: -30px !important; margin-right: -30px !important;">
            <div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
                <div id="users">
                    <div class="col-xs-12">
                        <div class="card" style="margin-bottom: 0px !important;">
                            <div class="header bg-indigo">
                                <h2 class="align-center">
                                    Pesquisar Endereço
                                    <small>Aqui você pode encontrar qualquer endereço cadastrado em seu catálogo...</small>
                                </h2>
                            </div>
                        </div>
                    </div>

                    <div class="col-xs-12">
                        <div style="background: #eeeeee; padding-top: 10px; padding-left: 10px; padding-right: 10px; padding-bottom: 3px;">
                            <div class="input-group" style="margin-bottom: 0px !important;">
                                <div class="form-line">
                                    <input type="text" class="form-control search align-center" id="nameSearchAddress" placeholder="Pesquise por endereços cadastrado em seu catálogo...">
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col-xs-12" >
                        <ul class="list list-search-address" id="target_ul">
                            <li>
                                <h3 class="addressStreet">Test</h3>
                                <p class="neighborhoodStreet">Test</p>
                            </li>
                        </ul>
                    </div>

                    <div class="col-xs-12">
                        <div class="btn-group btn-group-justified" role="group" aria-label="Justified button group">
                            <a href="javascript:void(0);" class="btn bg-indigo waves-effect sort" role="button" data-sort="name">CLASSIFICAR POR NOME</a>
                            <a href="javascript:void(0);" class="btn bg-indigo waves-effect" role="button" id="sendSearchAddress">ATUALIZAR</a>
                            <a href="javascript:void(0);" class="btn bg-indigo waves-effect" role="button">COPIAR PARA FORMULARIO</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

Thank you very much for helping me, I'm trying to do this for two long days... Success Data (finalData) returned by Ajax

[{
    "addressStreet": "Rua Baltazar Lorenzetto",
    "neighborhoodStreet": "Jardim Brasil",
    "latStreet": "Esperando latitude",
    "lngStreet": "Esperando longitude",
    "postalCodeStreet": "18214-490",
    "cityStreet": "Itapetininga",
    "stateStreet": "São Paulo",
    "id": "5a90b6b5c59ccc00148766b1"
}, {
    "addressStreet": "Rua Doutor Campos Sales",
    "neighborhoodStreet": "Centro",
    "latStreet": "-23.588984",
    "lngStreet": "-48.050931",
    "postalCodeStreet": "Esperando código postal",
    "cityStreet": "Itapetininda",
    "stateStreet": "São Paulo",
    "id": "5a94332d03d2a4001407a07c"
}, {
    "addressStreet": "Rua José de Almeida Carvalho",
    "neighborhoodStreet": "Centro",
    "latStreet": "-23.5785848",
    "lngStreet": "-48.027667",
    "postalCodeStreet": "18200-354",
    "cityStreet": "Itapetininga",
    "stateStreet": "São Paulo",
    "id": "5a948a0f03d2a4001407a07d"
}, {
    "addressStreet": "Esperando endereço...",
    "neighborhoodStreet": "Esperando bairro...",
    "latStreet": "Esperando latitude",
    "lngStreet": "Esperando longitude",
    "postalCodeStreet": "Esperando código postal",
    "cityStreet": "Esperando cidade",
    "stateStreet": "Esperando estado",
    "id": "5a9eb0e4a086fb0014b65b45",
    "term": "Rua Ba"
}, {
    "addressStreet": "Esperando endereço...",
    "neighborhoodStreet": "Esperando bairro...",
    "latStreet": "Esperando latitude",
    "lngStreet": "Esperando longitude",
    "postalCodeStreet": "Esperando código postal",
    "cityStreet": "Esperando cidade",
    "stateStreet": "Esperando estado",
    "id": "5a9eb0e5a086fb0014b65b46",
    "term": "Rua Bal"
}, {
    "addressStreet": "Esperando endereço...",
    "neighborhoodStreet": "Esperando bairro...",
    "latStreet": "Esperando latitude",
    "lngStreet": "Esperando longitude",
    "postalCodeStreet": "Esperando código postal",
    "cityStreet": "Esperando cidade",
    "stateStreet": "Esperando estado",
    "id": "5a9eb0e7a086fb0014b65b47",
    "term": "Rua Balta"
}, {
    "addressStreet": "Esperando endereço...",
    "neighborhoodStreet": "Esperando bairro...",
    "latStreet": "Esperando latitude",
    "lngStreet": "Esperando longitude",
    "postalCodeStreet": "Esperando código postal",
    "cityStreet": "Esperando cidade",
    "stateStreet": "Esperando estado",
    "id": "5a9eb135a086fb0014b65b4b"
}, {
    "addressStreet": "Esperando endereço...",
    "neighborhoodStreet": "Esperando bairro...",
    "latStreet": "Esperando latitude",
    "lngStreet": "Esperando longitude",
    "postalCodeStreet": "Esperando código postal",
    "cityStreet": "Esperando cidade",
    "stateStreet": "Esperando estado",
    "id": "5a9eb136a086fb0014b65b4c"
}, {
    "addressStreet": "Esperando endereço...",
    "neighborhoodStreet": "Esperando bairro...",
    "latStreet": "Esperando latitude",
    "lngStreet": "Esperando longitude",
    "postalCodeStreet": "Esperando código postal",
    "cityStreet": "Esperando cidade",
    "stateStreet": "Esperando estado",
    "id": "5a9eb136a086fb0014b65b4d"
}, {
    "addressStreet": "Esperando endereço...",
    "neighborhoodStreet": "Esperando bairro...",
    "latStreet": "Esperando latitude",
    "lngStreet": "Esperando longitude",
    "postalCodeStreet": "Esperando código postal",
    "cityStreet": "Esperando cidade",
    "stateStreet": "Esperando estado",
    "id": "5a9eb15aa086fb0014b65b50"
}]

Response in my console after click in List

elements.js:85 (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
elements.js:189 (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
elements.js:174 Selected address is:  
            Rua Baltazar Lorenzetto
             Jardim Brasil

Try this

              $("#target_ul").on("click", "li", function(event) {
                    var self = $(this);         // Storing the reference of the element
                    ...................... // Your code as is
                    ......................
                    // Add Selected Address In Notification
                    var selectedAddress = $( self ).text();       // Using the reference of the stored element
                    ....................... // Your code as is
                    .......................

To someone who was in the same doubt as I, analyzing more about what our friend @AkshayKhandelwal told me. I was trying to request information that is no longer the same from the beginning of the Api Get. By getting a specific target, we lose access to our raw JSON access, returned at the beginning of the function. By solution, I decided to choose to build a controller using ANGULAR JS, utilizing this method obtaining our event becomes much more manipulative and scaleable.

// Query Address In Catalog
$('#openSearchAddress').click(function() { 
    // Start Modal
    $('#modalSearchAddress')
       .modal('show')
    ;
});

The call of modal remains the same

angular.module('YourModuleName', [You can extend it using other libraries])
.controller('MyCtrl', function ($scope, $http) {
    $http({
        method: "GET",
        url: "Your API Link"
    }).then(function mySuccess(response) {
        // Print JSON in console
        // $scope.myWelcome = response.data;

        $scope.iconType = 'fa fa-circle-o';

        $scope.data = {
            showDelete: false
        };

        $scope.edit = function (item) {
            alert('Edit Item: ' + item.addressStreet);
        };

        $scope.clicker = function (item) {
            alert('Clicked chevron: ' + item.addressStreet)
        };
        $scope.share = function (item) {
            alert('Share Item: ' + item.addressStreet);
        };

        $scope.moveItem = function (item, fromIndex, toIndex) {
            $scope.items.splice(fromIndex, 1);
            $scope.items.splice(toIndex, 0, item);
        };

        $scope.onItemDelete = function (item) {
            $scope.items.splice($scope.items.indexOf(item), 1);
        };

        $scope.circleClicked = function (item) {
            alert('You selected Item: ' + item.addressStreet);
        }

        // Set Scope Contains Response Data
        $scope.items = response.data;
    }, function myError(response) {
        $scope.myWelcome = response.statusText;
    });
});

I had to restore our structure on the front end, you can add pagination, query, filters, highlights, whatever you want here. The style sheet you can customize to your liking :]

            <div class="col-xs-12">
                <ul class="list-search-address">
                    <li ng-repeat="item in items | filter : search" item="item" href="#/item/{{item.id}}" style="display: block; background-color: #eee; padding: 10px; box-shadow: inset 0 1px 0 #fff;">
                        <h3 style="font-size: 16px; margin: 0 0 0.3rem; font-weight: normal; font-weight: bold;">
                            <i ng-class="iconType" ng-mousedown="iconType='fa fa-check-circle-o'" ng-mouseup="iconType='fa fa-circle-o'" ng-click="circleClicked(item)"></i>{{ item.addressStreet }}</h3>
                        <p>{{ item.neighborhoodStreet }}</p>
                    </li>
                </ul>
            </div>

Thanks for enlightening my ideas xD

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