Open Closed

Why the JS function doesn't work #6112


0
rodrigosturm created

Hello,

I'm creating buttons in real time with this code:

 $('#OpenCidadeVanLegalLookupTableButton').click(function () {
            _cidadeVanLegalLookupTableModal.open({ id: 0, displayName: $('#cidadeVanLegalDescricao').val() }, function (data) {
                $("#divCidades").append("<button type='button' name= 'btn_RemoverCidade' value='" + data.id + "' class='btn btn_RemoverCidade m-btn--pill ' m-btn m-btn--custom m-btn--bolder m-btn--uppercase '><i class='fa fa-close'></i>" + data.displayName + "</button>");               
                CidadesEscolhidas = CidadesEscolhidas + "," + data.id;
                $("#cidadeVanLegalId").val(CidadesEscolhidas);
            });
        });

And it's working!

But, i need to remove this buttons when its clicked. and I use this code above, but Its not work. I use this a lot in my codes, but it is the first time I use in a Modal page, there are any diference between regular page and modal page in this case?

 $('.btn_RemoverCidade').on("click", function () {
            var value = $(this).attr('value');
            RemoveCidade(value);
            $(this).remove();
        });

image.png

image.png

Att,


6 Answer(s)
  • 0
    ismcagdas created

    Hi @rodrigosturm

    Your code seems fine. Do you have any javascript error on the browser console ?

  • 0
    rodrigosturm created

    No, JS error.

    But the button dont get the right event Click()

    I Assume, this div#Modal_2314321432432.modal.fade.show is confunding the JS.

    image.png

  • 0
    ryancyq created

    can you share the code for CidadeVanLegalLookupTableModal?

    if your realtime button adding/removing logic is not specific to only a view/page. You can move these customisation into the mod itself to have better control over the modal lifecycle.

  • 0
    rodrigosturm created

    Hi Ryancyq,

    All my code is in the Modal page ( _createOrEditModal.js, i generated this on Rad Tool). All my code:

    (function ($) {
        app.modals.CreateOrEditAnuncioModal = function () {
    
            var _anunciosService = abp.services.app.anuncios;
            var CidadesEscolhidas = "";
    
            var _modalManager;
            var _$anuncioInformationForm = null;
            var $jcropApi = null;
            var uploadedFileName = null;
            var SelecionouFoto = false;
    
            var _userLookupTableModal = new app.ModalManager({
                viewUrl: abp.appPath + 'App/Anuncios/UserLookupTableModal',
                scriptUrl: abp.appPath + 'view-resources/Areas/App/Views/Anuncios/_UserLookupTableModal.js',
                modalClass: 'UserLookupTableModal'
            });
    
            var _cidadeVanLegalLookupTableModal = new app.ModalManager({
                viewUrl: abp.appPath + 'App/Anuncios/CidadeVanLegalLookupTableModal',
                scriptUrl: abp.appPath + 'view-resources/Areas/App/Views/Anuncios/_CidadeVanLegalLookupTableModal.js',
                modalClass: 'CidadeVanLegalLookupTableModal'
            });
    
            var _faculdadeLookupTableModal = new app.ModalManager({
                viewUrl: abp.appPath + 'App/Anuncios/FaculdadeLookupTableModal',
                scriptUrl: abp.appPath + 'view-resources/Areas/App/Views/Anuncios/_FaculdadeLookupTableModal.js',
                modalClass: 'FaculdadeLookupTableModal'
            });
    
            var _assinaturaLookupTableModal = new app.ModalManager({
                viewUrl: abp.appPath + 'App/Anuncios/AssinaturaLookupTableModal',
                scriptUrl: abp.appPath + 'view-resources/Areas/App/Views/Anuncios/_AssinaturaLookupTableModal.js',
                modalClass: 'AssinaturaLookupTableModal'
            });
    
            this.init = function (modalManager) {
                _modalManager = modalManager;
    
    			var modal = _modalManager.getModal();
                modal.find('.date-picker').datetimepicker({
                    locale: abp.localization.currentLanguage.name,
                    format: 'L'
                });
    
                $('#ChangeProfilePictureModalForm input[name=ProfilePicture]').change(function () {
                    $('#ChangeProfilePictureModalForm').submit();
                });
                $('#ChangeProfilePictureModalForm').ajaxForm({
                    beforeSubmit: function (formData, jqForm, options) {
    
                        var $fileInput = $('#ChangeProfilePictureModalForm input[name=ProfilePicture]');
                        var files = $fileInput.get()[0].files;
    
                        if (!files.length) {
                            return false;
                        }
    
                        var file = files[0];
    
                        //File type check
                        var type = '|' + file.type.slice(file.type.lastIndexOf('/') + 1) + '|';
                        if ('|jpg|jpeg|png|gif|'.indexOf(type) === -1) {
                            abp.message.warn(app.localize('ProfilePicture_Warn_FileType'));
                            return false;
                        }
    
                        //File size check
                        if (file.size > 5242880) //5MB
                        {
                            abp.message.warn(app.localize('ProfilePicture_Warn_SizeLimit', app.maxProfilPictureBytesUserFriendlyValue));
                            return false;
                        }
                        
                        return true;
                    },
                    success: function (response) {
                        if (response.success) {
                            var $profilePictureResize = $('#ProfilePictureResize');
    
                            var profileFilePath = abp.appPath + 'Temp/Downloads/' + response.result.fileName + '?v=' + new Date().valueOf();
                            uploadedFileName = response.result.fileName;
                           
                            SelecionouFoto = true;
                            if ($jcropApi) {
                                $jcropApi.destroy();
                            }
    
                            $profilePictureResize.show();
                            $profilePictureResize.attr('src', profileFilePath);
                            $profilePictureResize.attr('originalWidth', response.result.width);
                            $profilePictureResize.attr('originalHeight', response.result.height);
    
                            $profilePictureResize.Jcrop({
                                setSelect: [0, 0, 100, 100],
                                aspectRatio: 1,
                                boxWidth: 400,
                                boxHeight: 400
                            }, function () {
                                $jcropApi = this;
                            });
    
                        } else {
                            abp.message.error(response.error.message);
                        }
                    }
                });
    
               
                _$anuncioInformationForm = _modalManager.getModal().find('form[name=AnuncioInformationsForm]');
                _$anuncioInformationForm.validate();
            };
    
    		$('#OpenUserLookupTableButton').click(function () {
                    var anuncio = _$anuncioInformationForm.serializeFormToObject();
                    _userLookupTableModal.open({ id: anuncio.userId, displayName: anuncio.userName }, function (data) {
                    _$anuncioInformationForm.find('input[name=userName]').val(data.displayName);
                    _$anuncioInformationForm.find('input[name=userId]').val(data.id);
                });
            });
    		
    		$('#ClearUserNameButton').click(function () {
                    _$anuncioInformationForm.find('input[name=userName]').val(''); 
                    _$anuncioInformationForm.find('input[name=userId]').val(''); 
            });
    		
            $('#OpenFaculdadeLookupTableButton').click(function () {
    
                var anuncio = _$anuncioInformationForm.serializeFormToObject();
    
                _faculdadeLookupTableModal.open({ id: anuncio.faculdadeId, displayName: anuncio.faculdadeDescricao }, function (data) {
                    _$anuncioInformationForm.find('input[name=faculdadeDescricao]').val(data.displayName); 
                    _$anuncioInformationForm.find('input[name=faculdadeId]').val(data.id); 
                });
            });
    		
    		$('#ClearFaculdadeDescricaoButton').click(function () {
                    _$anuncioInformationForm.find('input[name=faculdadeDescricao]').val(''); 
                    _$anuncioInformationForm.find('input[name=faculdadeId]').val(''); 
            });
    		
            $('#OpenAssinaturaLookupTableButton').click(function () {
    
                var anuncio = _$anuncioInformationForm.serializeFormToObject();
    
                _assinaturaLookupTableModal.open({ id: anuncio.assinaturaId, displayName: anuncio.assinaturaPlano }, function (data) {
                    _$anuncioInformationForm.find('input[name=assinaturaPlano]').val(data.displayName); 
                    _$anuncioInformationForm.find('input[name=assinaturaId]').val(data.id); 
                });
            });
    		
    		$('#ClearAssinaturaPlanoButton').click(function () {
                    _$anuncioInformationForm.find('input[name=assinaturaPlano]').val(''); 
                    _$anuncioInformationForm.find('input[name=assinaturaId]').val(''); 
            });
            
            //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            // GENERATE THE BUTTONS
            //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
            $('#OpenCidadeVanLegalLookupTableButton').click(function () {
                _cidadeVanLegalLookupTableModal.open({ id: 0, displayName: $('#cidadeVanLegalDescricao').val() }, function (data) {
                    $("#divCidades").append("<button type='button' name= 'btn_RemoverCidade' value='" + data.id + "' class='btn btn_RemoverCidade m-btn--pill ' m-btn m-btn--custom m-btn--bolder m-btn--uppercase '><i class='fa fa-close'></i>" + data.displayName + "</button>");               
                    CidadesEscolhidas = CidadesEscolhidas + "," + data.id;
                    $("#cidadeVanLegalId").val(CidadesEscolhidas);
                });
            });
                
                //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
                //Removing the BUTTONS
                //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
                
            $('.btn_RemoverCidade').on("click", function () {
                var value = $(this).attr('value');
                RemoveCidade(value);
                $(this).remove();
            });
    
            function RemoveCidade(id){
                CidadesEscolhidas = str.replace("," + id, "");
                $("#cidadeVanLegalId").val(CidadesEscolhidas);
            }
    
            this.save = function () {
                if (!_$anuncioInformationForm.valid()) {
                    return;
                }
                var anuncio = _$anuncioInformationForm.serializeFormToObject();       
                console.log(anuncio);
                if (SelecionouFoto) {
                    var resizeParams = {};
                    if ($jcropApi) {
                        resizeParams = $jcropApi.getSelection();
                    }
                    var containerWidth = $jcropApi.getContainerSize()[0];
                    var containerHeight = $jcropApi.getContainerSize()[1];
    
                    var originalWidth = containerWidth;
                    var originalHeight = containerHeight;
    
                    if ($('#ProfilePictureResize')) {
                        originalWidth = parseInt($('#ProfilePictureResize').attr("originalWidth"));
                        originalHeight = parseInt($('#ProfilePictureResize').attr("originalHeight"));
                    }
    
                    var widthRatio = originalWidth / containerWidth;
                    var heightRatio = originalHeight / containerHeight;
                   
                    anuncio.height = parseInt(resizeParams.h * heightRatio);
                    anuncio.width = parseInt(resizeParams.w * widthRatio);
                    anuncio.x = parseInt(resizeParams.x * widthRatio);
                    anuncio.y = parseInt(resizeParams.y * heightRatio);
                    anuncio.fileName = uploadedFileName;
                }
    
                _modalManager.setBusy(true);
                _anunciosService.createOrEdit(anuncio).done(function () {
                   abp.notify.info(app.localize('SavedSuccessfully'));
                   _modalManager.close();
                   abp.event.trigger('app.createOrEditAnuncioModalSaved');
    			 }).always(function () {
                   _modalManager.setBusy(false);
    			});
            };
        };
    })(jQuery);
    
  • 0
    ryancyq created

    You should move real time button generation into init() of 'view-resources/Areas/App/Views/Anuncios/_CidadeVanLegalLookupTableModal.js

    For example, the following should be in the js of the modal instead.

    $("#divCidades").append("<button type='button' name= 'btn_RemoverCidade' value='" + data.id + "' class='btn btn_RemoverCidade m-btn--pill ' m-btn m-btn--custom m-btn--bolder m-btn--uppercase '><i class='fa fa-close'></i>" + data.displayName + "</button>");               
    CidadesEscolhidas = CidadesEscolhidas + "," + data.id;
    $("#cidadeVanLegalId").val(CidadesEscolhidas);
    

    and

    //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    //Removing the BUTTONS
    //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        
    $('.btn_RemoverCidade').on("click", function () {
        var value = $(this).attr('value');
        RemoveCidade(value);
        $(this).remove();
    });
    
    function RemoveCidade(id){
        CidadesEscolhidas = str.replace("," + id, "");
        $("#cidadeVanLegalId").val(CidadesEscolhidas);
    }
    

    If you look at how _modal.open(arg1, arg2) works at https://github.com/aspnetzero/aspnet-zero-core/blob/6f790fdc31bbb2360f7be5cfdd83889eb16e496a/aspnet-core/src/MyCompanyName.AbpZeroTemplate.Web.Mvc/wwwroot/Common/Scripts/ModalManager.js#L106-L109

    arg2 is actually only called when _modal.setResult() is called. setResult() is usually called when modal is saving/closing.

  • 0
    rodrigosturm created

    I understand, and it didnt work.

    Te creation is perfect!

    the only problem is the remove Button on event click, I Try force put the function on the onclick(). But i Still have problems...

    image.png

    image.png