javascript does not function after dom is updated [duplicate] - javascript

This question already has answers here:
jQuery doesn't work after content is loaded via AJAX
(9 answers)
Closed 7 years ago.
I got a webpage that updates its content using ajax/json and handlebars. Now i want to use bootstrap-datepicker for my date fields, but after updating the DOM with handlebars, the javascript event does not work.
My javascript
$(function(){
var refresher = function () {
$.getJSON( "{% url 'characters:journal_json' 1 %}", function(obj) {
refresh_timer = obj.refresh_timer * 1000;
setTimeout(refresher, refresh_timer);
if (obj.content) {
// do shit with content and data
var source = $("#JournalTemplate").html();
var template = Handlebars.compile(source);
var html = template(obj.content);
$("#JournalContent").replaceWith(html);
}
});
};
setTimeout(refresher, 300); // 0.3 seconds
});
$('.datepicker').datepicker({
format: "mm-dd-yyyy",
autoclose: true
});
Handlebars template (will be expanded after i solve this problem):
<form class="form-inline" action="" method="GET" id="FilterForm">
<input class="form-control input-sm datepicker" id="id_end_date" name="end_date" type="text" value="05-26-2015" />
<button type="submit" class="btn btn-primary btn-sm">Filter</button>
</form>

Try this way :
$('body').on('focus', '.datepicker', function () {
$(this).datepicker({
format: "mm-dd-yyyy",
autoclose: true
});
});
With on the event is also triggered for dynamic elements

I did little trick, please try this,
$(function(){
var refresher = function () {
$.getJSON( "{% url 'characters:journal_json' 1 %}", function(obj) {
refresh_timer = obj.refresh_timer * 1000;
setTimeout(refresher, refresh_timer);
if (obj.content) {
// do shit with content and data
var source = $("#JournalTemplate").html();
var template = Handlebars.compile(source);
var html = template(obj.content);
$("#JournalContent").replaceWith(html);
bindDatepicker(); // *** Here I am binding again...
}
});
};
setTimeout(refresher, 300); // 0.3 seconds
});
function bindDatepicker() {
$('.datepicker').datepicker({
format: "mm-dd-yyyy",
autoclose: true
});
}
This code binds datepicker every time when HTML is updated.
Hope it helps.

First of all bootstrap uses jQuery, so please confirm that you are putting jQuery script before bootstrap.js. After that write your own script inside tag followed by self executing/ anonymous function, called as IIFE(Immediately Invoked Function Expression) in JavaScript. So, this is a good approach to write scripts always. Please try as below.
(function(){
----- Your Code ----
})();
And definitely you will get rid of all these. Thanks.

Related

How to pass controller data (php) to the content blocks of ContentBuilder?

i've bought the latest ContentBuilder.js from innovastudio.
I've integrated it in my cms and is working fine.
Now i have created new static blocks this works fine also.
But now i try to make dynamic blocks with php data passed from the controller when the page loads but can't seems to make it work.
I know php loads before javascript .But i'm a little bit stuck.
Does someone already have worked with contentbuilder.js and could someone please guide me how to resolve this issue please?
I'm working in laravel 5.8 , i did getelementbyid with javascript and replace the value with the dynamic value .
This works but only for single rows and not collections.-
<script type="text/javascript">
jQuery(document).ready(function ($) {
var DBaddress = '{{$settings[0]['address']}}';
var DBnumber = '{{$settings[0]['number']}}';
var DBpostalcode = '{{$settings[0]['postal_code']}}';
var DBtown = '{{$settings[0]['town']}}';
var DBtel = '{{$settings[0]['telephone']}}';
var DBemail = '{{$settings[0]['email']}}';
var obj = $.contentbuilder({
container: '.container_edit',
imageselect: 'admin/laravel-filemanager',
cellFormat: '<div class="col-md-12"></div>',
rowFormat: '<div class="row"></div>',
framework: 'bootstrap',
});
$('#btnViewSnippets').on('click', function () {
obj.viewSnippets();
});
$('#btnViewHtml').on('click', function () {
obj.viewHtml();
});
/*$('#btnSave').on('click', function () {
save(obj.html());
});*/
document.getElementById("address").innerHTML= DBaddress;
document.getElementById("number").innerHTML= DBnumber;
document.getElementById("postalcode").innerHTML= DBpostalcode;
document.getElementById("town").innerHTML= DBtown;
document.getElementById("tel").innerHTML= DBtel;
document.getElementById("email").innerHTML= DBemail;
});
</script>
Here the section where the page builder is set :
#section('content')
<div class="container_edit">
{!! $page->contentBuilder !!}
</div>
#if( basename(url()->current()) !== $page->slug)
<div class="is-tool" style="position:fixed;width:210px;height:50px;border:none;top:250px;bottom:50px;left:auto;right:30px;text-align:right;display:block">
<button id="btnViewSnippets" class="classic" style="width:70px;height:50px;">+ Add</button>
<button id="btnViewHtml" class="classic" style="width:70px;height:50px;">HTML</button>
<button id="btnSave" data-id="{{$editPageDetails[0]->uuid}}" class="classic" style="width:70px;height:50px;">SAVE</button>
</div>
#endif
#endsection
This is how i could manage to make it work, but again this is for single rows. I would like to have the complete collection so i could create dynamic blocks

passing variables to function with jquery

I'm new to javascript although I do use PHP.
I'm having issues passing variables using javascript/jquery on an onclick event on a href.
I'm pulling json data from a remote URL and there are 3 parameters that need to go with each request.
Date, price and currency.
I have a function to build the URL that looks like this:
function getIndexData(date, price, currency){
ajaxURL = "/data/"+date+"/"+price+"/"+currency+"";
}
This works well and builds the URL I need.
However, I have a jquery datepicker on the page to change the date to whatever I want which looks like:
$(function () {
$("#datepicker").datepicker(
{
dateFormat: 'yymmdd',
onSelect: function (date) {
getIndexData(date, price, currency )
}
}
);
});
Even if price and currency have previously been set they are now 'undefined'.
I have the same issue with the onclick events - if I try to send the price or the currency using (for example):
NET</span>
price and currency are undefined.
Is there a way I can send only one of the variables to my function whilst retaining the already existent values?
Apologies for what must be a really basic question. I'm just new to this and I've obviously misunderstood something along the way.
Ok so here is the updated answer. As you can see, if variables are declared in the global scope of the code, the date picker function will have access to it. I think it previously did not work because the html was wrong. I deleted all of the html and included only the date picker and if you test it in the browser, you will see that in the console the price, currency variables are available inside date picker onSelect function and you can also execute the function getIndexData inside it. I've assigned the function to a variable that way you can use the variable getIndexData if you want to use the function.
<html>
<head>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div class="col-sm-5 index-grid">
<span class="grid-label">Price</span>
<span class="btn btn-grid">CLOSE</span>
<span class="btn btn-grid">RETURN</span>
<span class="btn btn-grid">NET</span>
</div>
<p>Date: <input type="text" id="datepicker"></p>
</body>
</html>
<script>
var ajaxURL;
var indexDate = "2017-08-20"
var indexPrice = "closeprice";
var indexCurrency = "EUR";
var getIndexData = function (indexDate, indexCurrency, indexPrice) {
ajaxURL = "/data/" + indexDate + "/" + indexPrice + "/" + indexCurrency + "";
alert(ajaxURL);
}
$(document).ready(function() {
$(function() {
$("#datepicker").datepicker({
dateFormat: 'yymmdd',
onSelect: function(date) {
console.log(date);
console.log(indexPrice);
console.log(indexCurrency);
console.log(getIndexData);
}
});
});
});
</script>
If you declared price and currency outside of :
$(function () {
$("#datepicker").datepicker(
{
dateFormat: 'yymmdd',
onSelect: function (date) {
getIndexData(date, price, currency )
}
}
);
});
Then what you need to do is use the "this" keyword to access the values of price and currency. Just like the example below.
You may also want to check this link for more insight : https://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/
$(function () {
$("#datepicker").datepicker(
{
dateFormat: 'yymmdd',
onSelect: function (date) {
getIndexData(date, this.price, this.currency )
}
}
);
});

Call a JS function from and external file passing a parameter on page load

I'm kind of new to JS yet, so I'd like to know if there is anyway to do this:
main.js:
$(function () {
$('.delete_btn').click(function () {
var confirmation = confirm('Deseja remover este evento?');
if (!confirmation) return false;
})
})
function updateIsoDate(date) {
$('.datepicker').datepicker('setDate', date);
}
I'm already calling a function of it onload, but It doesn't required and specific thing.
events.ejs:
...
<div class="form-group">
<label for="date">Data do Evento</label>
<input type="text" class="form-control datepicker" id="date"name="date">
<input type="hidden" id="dateInfo" name="date" value=' <%= event.date %>'>
</div>
...
<script>
$(document).ready(function () {
updateIsoDate($('#dateInfo').val());
});
<script>
Can I call a function from a external file passing a parameter to it?
I don't know if I need to add scr="js/main.js" to my "script" tag cuz It's already previously loaded
So I'm trying to change my IsoDate format to display into my datepicker. It's working but I want to make the page a little cleaner calling it from another file.
Kudos:
First!Thanks everyone and especially Jonas w that made me realise something was wrong, and sorry for wasting your time.
Answer:
if you already inclued the js file previously, ex:
<script src="/js/main.js"></script>
You can call you function from the script tag, and using
$(function () {'code here'}
or
$(window).on('load', function () {'code here'}
You'll call it where the page is ready(1st one) or completely loaded(2nd one).
So calling your function and passing the argument/parameter, would be:
<script src="/js/main.js"></script>
<script>
$(window).on('load', function () {
myFunc(arg);
}
</script>
Why don't you move
<script>
$(document).ready(function () {
updateIsoDate($('#dateInfo').val());
});
<script>
to your main.js, so in result you will have:
function updateIsoDate(date) {
$('.datepicker').datepicker('setDate', date);
}
$(function () {
$('.delete_btn').click(function () {
var confirmation = confirm('Deseja remover este evento?');
if (!confirmation) return false;
})
$(document).ready(function () {
updateIsoDate($('#dateInfo').val());
});
})
Simpy do:
window.onload=function(){
coolonloadfunction("p1", "p2");
}
Or in Jquery:
$(document).ready(function(){
coolonloadfunction(" p1", "p2");
});
This executes:
function coolonloadfunction(a,b){
alert(a);//p1
alert(b);//p2
}
That may be in a different file, may be loaded with:
<script src=" scriptwithcoolonloadfunction.js"></script>
Keep in mind that the external file should be placed in front of the code that calls functions in the file
This answers the headline, however your real question is a bit unclear for me. Please specify
events.ejs:
I've add the javascript file
<script src="/js/main.js"></script>
Here the input where the value is
<div class="form-group">
<label for="date">Data do Evento</label>
<input type="text" class="form-control datepicker dp-add" id="date" name="date">
<input type="hidden" id="dateInfo" name="date" value=' <%= event.date %>' required>
</div>
...
Then used $(window).on('load', function() to pass the argument and call the function inside the main.js file
<script>
$(window).on('load', function() {
// Formating IsoDate to be displayed and setting into the datepicker
updateIsoDate($('#dateInfo').val());
});
</script>
main.js:
function updateIsoDate(date) {
$('.datepicker').datepicker('setDate', date);
}

Backbone can't see a key passed to the template [duplicate]

This question already has answers here:
Underscore template throwing variable not defined error
(2 answers)
Closed 7 years ago.
I have a very simple code in order to use a backbone/underscore template.
HTML:
<script type="text/template" id="search_template">
<div>Name comes here: <h4><%=name%></h4></div>
<input type="text" id="search_input" />
<input type="button" id="search_button" value="Search" />
</script>
<div id="search_container"></div>
JS:
$(function(){
var SearchView = Backbone.View.extend({
initialize: function(){
this.render();
},
render: function(){
var tmpl = $('#search_template').html(),
compiled = _.template(tmpl, { name:'hello' });
$(this.el).html(compiled);
}
});
var search_view = new SearchView({ el: "#search_container" });
});
The problem is it can't see the key "name" which should be passed into template. I still don't figure out why.
The whole code sample is located here: http://plnkr.co/edit/7fV2azTh6cpjmUxIBHvJ?p=preview
You are not using Underscore's template method correctly.
The compilation step is not where you pass in your parameters to be replaced by the template. Rather, the compilation step produces a function. The result of invoking the compiled function, with your view model parameters as the first argument, will return a string of your template with the replaced values of your view model.
render: function () {
var tmpl = $('#search_template').html(),
compiled = _.template(tmpl);
this.$el.html(compiled({ name:'hello' }));
}
An additional point: Notice how a Backbone View already gives us a convenient this.$el, so we don't need to do the $(this.el) step again.
change
compiled = _.template(tmpl, { name:'hello' });
to
compiled = _.template(tmpl)({ name:'hello' });
_.template returns function that accepts data to be inserted into template
http://plnkr.co/edit/GqFBvepfukIwDGLQa8Ki?p=preview

Using Razor and javascript within each other

I want to use a javascript variable in Razor like this :
my html:
#{List<AddTempViewModel> tempsToView = new List<AddTempViewModel>();
tempsToView = (List<AddTempViewModel>)ViewData["tempsToView"];}
#if (tempsToView != null)
{
#foreach (var item in tempsToView)
{
<a class="click" id="#item.TempDocumentId">
<img id="leftSideBarElement" src="#item.TempDocumentAddressUrl" />
</a><br />
}
<form method="post" action="">
<input id="documentNumber" class="form-control" type="text" name=""
placeholder="Email" />
</form>
and my script :
<script>
$(document).ready(function () {
$(".click").click(function () {
var divID = $(this).attr('id');
alert(divID);
var docName = #tempsToView[divID].TempDocumentId
$("#documentNumber").val(docName);
});
});
</script>
but I can't set the index of #tempsToView with divID.
please help me what to do except this.
thank you.
You can't set a Razor variable based on something that's happening in JavaScript. Razor runs server-side, while JavaScript runs client-side, after all Razor has already been run.
Its not really clear what you need but If I get you right... I used to make this mix of Razor and Js but in the long run I realize 2 things:
It looks pretty ugly
It won't run if you move your js code to a separate .js file, because
the Razor engine does not process JS files.
So a simple and elegant solution would be to use data attributes:
#foreach (var item in tempsToView)
{
<a class="click" id="#item.TempDocumentId"
data-document-name="#item.TempDocumentName"
data-document-isbn="#item.TempDocumentIsbn">
<img id="leftSideBarElement" src="#item.TempDocumentAddressUrl" />
</a><br />
}
And then just get the data-property you need like:
$(document).ready(function () {
$(".click").click(function () {
var divID = $(this).attr('id');
alert(divID);
var docName = $(this).attr('data-document-name');
var docIsbn = $(this).attr('data-document-isbn');
//and any other property you may need
$("#documentNumber").val(docName);
});
});
That way you keep, all your HTML/Razor and JS separate, and still functional, a clean code and every element is self-sufficient.
<script>
$(document).ready(function () {
var divID = $(this).attr('id');
alert(divID);
var documentName = $(#Html.Raw(JsonConvert.SerializeObject(tempsToView )))[divID];
console.log(documentName);
});
</script>

Categories

Resources