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 )
}
}
);
});
Related
Please can someone please explain how this code works? It's a trivial piece of code but I don't understand/appreciate how the Option
beforeShowDay
, that calls a function works.
The DisableDates Option calls function DisableDates(date) (that seemingly) takes in a date parameter - and I can't understand how this date parameter is being passed?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link
rel="stylesheet"
href="http://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 id="date"></div>
<script>
$(function () {
var dates = ["08/11/2020", "09/11/2020", "10/11/2020", "12/11/2020"];
$("#date").datepicker({
changeYear: true,
changeMonth: true,
dateFormat: "yy/mm/dd",
minDate: new Date("2020/10/01"),
maxDate: "+3m",
beforeShowDay: DisableDates,
});
function DisableDates(date) {
var string = jQuery.datepicker.formatDate("dd/mm/yy", date);
return [dates.indexOf(string) == -1];
}
});
</script>
</body>
</html>
jQuery datepicker internally calling that function and passing parameter also.
Consider below small demo where you can assign your function to another variable and use that variable to call your function with parameter.
// plugin sample code with options
function demo(options) {
// assign option values to plugin variables.
this.date = options.date;
this.beforeShowDay = options.beforeShowDay;
// trigger function which invoke callback function with parameters
this.triggerBeforeShowDay = function() {
// as we have this.beforeShowDay = options.beforeShowDay;
// below code will be same as DisableDates(this.date)
this.beforeShowDay(this.date);
}
// return plugin object
return this;
}
// Your callback function with parameter
function DisableDates(date) {
console.log(date)
}
// pass options values in plugin
let d = new demo({
date: new Date("2020/10/01"),
beforeShowDay: DisableDates
});
// trigger function : Note - this part would be done internally on text change event from jquery datepicker.
// For demo only we are manually calling it.
d.triggerBeforeShowDay();
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);
}
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.
I'm trying to set the default date in datepicker with a variable I pass into the html from PHP. Here's a simplified version of both my control file and form:
control file:
<?php
function render($template, $values = []) {
// extract variables into local scope
extract($values);
// render template
require("$template");
}
$default_date = date("m/d/Y") ;
$default_date = strtotime($default_date);
$default_date = $default_date + 604800;
$default_date = date("Y,m-1,d",$default_date);
render("index_month2_form.php",['default_date'=> $default_date]);
?>
and here is the form:
<!doctype html>
<html lang="en">
<head>
<?php print "$default_date"; ?>
<meta charset="utf-8">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="jqueryui/css/swanky-purse/jquery-ui-1.10.4.custom.css">
<script src="/jqueryui/jquery-1.11.1.min.js"> </script>
<script src="jqueryui/js/jquery-ui-1.10.4.custom.min.js"></script>
<script type="text/javascript">
$(function() {
$("#mydate").datepicker ({
onSelect: function(dateText, inst) {
var dateAsString = dateText;
var date = $('#mydate').val();
}
})
//.datepicker("setDate",new Date());
.datepicker("setDate",new Date(2014,10-1,17));
});
</script>
</head>
<body>
<p>Date: <input type="text" id="mydate"></p>
</body>
</html>
If I use the commented line for setDate I get the current date. If I use the line I have I get the date 7 days forward. When I print $default_date at the top of the form I get 2014,10-1,17 but I can't firgure out of way to pass this into the script. Others have suggested using
The better solution is to assign returned PHP date variable to jQuery variable.
This can be done by following
var phpDate = "<?php echo $default_date; ?>";
Now, you need to assign that to datepicker
$("#mydate").datepicker("setDate",phpDate);
This works...
using echo is the way to go.
I would rather put it in the script rather than the input
I assume $default_date === "2014,10-1,17"
$(function() {
$("#mydate").datepicker ({
onSelect: function(dateText, inst) {
var dateAsString = dateText;
var date = $('#mydate').val();
}
})
//.datepicker("setDate",new Date());
.datepicker("setDate",new Date(
<?php
$date = explode(',', $default_date);
echo $date[0] . ',' . $date[1] . ',' . $date[2];
?>
));
};
edit:
As rss81 noticed it, destructuring the string to rebuild the exact same string is quite dumb. I dont know what I was thinking...
Nevertheless I'll let it like this for educational purpose.
exploding the string enables us to get an array of the string of each chunk separated by a coma. You could use it to reorder the string. For instance if you wanted to transform "2014,10-1,17" to "10-1,2014,17" that would be done by echo $date[1].','.$date[0].','.$date[2]
Echo enables us to output the html page as we like, making it dynamic. So here we are preprocessing the date argument of the .datepicker() by php.
Just give the input the relative value
<input type="text" id="mydate" value="<?php echo $yourdate; ?>">
This will init datepicker with you date value
Hope this helped and my apologies if this is not what you were looking for
You can use <?php echo not in the script, but in the body, in some display:none element with id. And then just to get the date with javascript from that element and set to datapicker
You could pass the $default_date value in a data attribute of an html element. For example:
<p id="myDate" data-date="<?php echo $default_date; ?>"></p>
After that you can extract it with with Jquery like this:
var date = $("#myDate").data("date");
You need to set date format in javascript part because it's create and problem with date.
You can set it given below
$("#datepicker").datepicker("option", "dateFormat", "yy-mm-dd ");
I'm trying to add Datepicker to my online form as part of my student assessment. I'm very new to all this and I'm having issues . I've downloaded and linked to my jquery UI and I've typed the code as per the jquery UI website states but the calendar doesn't pop up on my form when I click in the Date field like it suggests, I've also taken examples from this site but I still can't get it to work.
<head>
<link href="javascript/jquery-ui-1.10.3.custom/css/south-street/jquery-ui-1.10.3.custom.css" rel="stylesheet">
<script src="javascript/jquery-ui-1.10.3.custom/js/jquery-1.9.1.js"></script>
<script src="javascript/jquery-ui-1.10.3.custom/js/jquery-ui-1.10.3.custom.js"></script>
<script>
function validate(){
date = document.getElementById("datePicker").value;
errors = "";
if (date == ""){
errors += "Please supply a valid DOB \n";
}
}
</script>
</head>
<body>
<form name= "myform" method="post" action="" class="booking">
<fieldset>
<div>
<label for="datePicker" class="fixedwidth">Date</label>
<input type="text" name="datePicker" id="datePicker"/>
</div>
</fieldset>
</body>
You need to call your code in ready or load function , or insert it to a function and call it in your main js file.
You have to have some jQuery code to initialize the datepicker, like
<script type="text/javascript">
$(function(){
$('#datePicker').datepicker();
});
</script>
Need to call datepicker on body load.
<script type="text/javascript">
$(document).ready(function(){
$("#datePicker").datepicker();
});
</script>
<script>
$(document).ready(function(){
$("#datePicker").datepicker();
});
function validate(){
date = document.getElementById("datePicker").value;
errors = "";
if (date == ""){
errors += "Please supply a valid DOB \n";
}
}
</script>
You are missing this code in your script
$(function() {
$( "#datepicker" ).datepicker();
});
First initialize the datepicker UI method.
$(document).ready(function(){
$("#datePicker").datepicker();
});
Since you are using jQuery, you get the value like
$("#datePicker").val();
Update:
To get the value after selecting it from datepicker
$(document).ready(function () {
$("#datePicker").datepicker({
onSelect: function (date) {
alert(date);
}
});
});
JSFiddle