I'm developing an application where I have some views that are loaded into my <section id="view">
via ajax.
The view loads normally, but functions that have been programmed with jQuery for all inputs, for example, do not work. As far as my logic allows me to observe, this is because the elements added by ajax are added to the DOM after the main script - which takes care of the inputs - is loaded so that it does not observe the new elements.
I'm currently copying and pasting the script
tag into all views, which is a maintenance bag and will be unfeasible when I launch the app, since I'll need to minify everything in app.min.js
.
What would be the solution for my case?
Remembering that if I change the attr('src')
of the script, Chrome warns me via console that it is an obsolete way of doing this.
Edit:
Assuming that this is my main.js
//Selector personalizado
//Nenhum select option vai funcionar sem isso!
$('.selector-input').click(function(){
var selector = $(this).children('.selector');
var pickerIcon = $(this).find('.input-text .picker .picker-icon .material-icons');
if(selector.css('display') == 'none'){
selector.fadeIn(100);
pickerIcon.addClass('rotated');
}
});
$('.selector .options .option').click(function(){
var content = $(this).text();
var optId = $(this).attr('data-opt');
var inputId = $(this).parents('.selector').attr('data-picker-id');
$('#' + inputId).text(content);
$('#' + inputId).attr('data-selected', optId);
$(this).parents('.selector').fadeOut(100);
$('.material-icons').removeClass('rotated');
});
$(function(){
//Caso seja empregador
if($('#view2')){
view = getUrlParameter('view') ? getUrlParameter('view') : window.location.href+="?view=newusers"
$.ajax({
method: "post",
url: "views/empregador/" + view + ".php",
data: {
auth: 'loadedbyajax'
}
}).done(function(data) {
$('#view2').html(data);
});
$('.user-profile-picture').each(function(){
$(this).css('background-image', "url('" + $(this).attr('data-bg') + "')");
});
}
});
And this is the server response (which will be added in my <section id="view2">
:
<div class="selector-input">
<div class="input-text">
<label>Estado</label>
<span class="picker">
<span id="estadoSelect" class="picked" data-selected="ES">
Espírito Santo</span>
<span class="picker-icon"><i class="material-icons">keyboard_arrow_down</i></span>
</span>
</div>
<div class="selector" data-picker-id="estadoSelect">
<div class="options">
<div class="option" data-opt="DF">Distrito Federal </div><div class="option" data-opt="ES">Espírito Santo</div><div class="option" data-opt="MG">Minas Gerais</div><div class="option" data-opt="RJ">Rio de Janeiro</div><div class="option" data-opt="SP">São Paulo</div> </div>
</div>
</div>