I have an HTML component and a javascript function:
function calculateTime(date1, date2) {
return date2 - date1;
}
<span>calculateTime(date1,date2);</span>
But this just results in the actual text 'calculateTime()' with the two dates in between.
How do I escape the text and make sure that the function is called?
Use as mentioned below:
HTML:
<span id="calculatedTime"></span>
JavaScript:
window.onload = function(){
document.getElementById('calculatedTime').innerHTML = date2-date1;
}
You can't automatically just add a javascript funciton name into html and expect it to run - like you've found, the browser interprets it as text. A way to achieve your desired function would be to add an id to the span, and add this to your js:
document.getElementById('time').innerHTML = calculateTime(date1,date2)
e.g.:
<script>
function calculateTime(date1, date2)
{
return date2-date1;
}
document.getElementById('time').innerHTML = calculateTime(date1,date2); //note that we need to SET date1 and date2 before this will work.
</script>
<html>
<span id="time">calculateTime(date1,date2);</span>
</html>
JSFiddle example: http://jsfiddle.net/34qL46z3/1
Related
Ok, so I have an MVC webapp. I've tried for hours to pass one simple variable from TransactionsDatePicker.cshtml to Transactions display.
I have an input with an id of 'transactionlookupdate'. I want to intercept it (input type is date).
I've managed to append the date to the link like this:
<script>
document.getElementById("buttoncontinue").addEventListener("click", function () {
dateSelected = document.getElementById("transactionlookupdate").value;
document.location.href = 'TransactionsDisplay' + '/' + dateSelected;
});
</script>
Now, what do I do in TransactionsDisplay (where I want to get the date) to store it in usable variable?!
So far I've tried like a 100 different ways, one that got me the closest was:
(top of TransactionsDisplay.cshtml)
#{
ViewBag.Title = "TransactionsDisplay";
Layout = "~/Views/Shared/_Layout.cshtml";
var dateSelected = Request.Url.Segments.Last();
}
and awful try at populating alert with dateSelected:
<script>
function myFunction() {
alert(dateSelected);
}
</script>
Any help would be appreciated!
Pass the date as url parameter in TransactionsDatePicker.cshtm
document.location.href = 'TransactionsDisplay' + '?date=' + dateSelected;
and extract in TransactionsDisplay at the end of the <body> element:
<script>
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const myDate = urlParams.get('date');
alert(myDate); // test alert
</script>
I have a few JavaScript functions like the one below...
<input type="text" id="myField">
<script>
$("#myField").val("10:20:30");
function doNotEditIt(fieldId){ // this function can't be edited!
var myVar = $("#" + fieldId).val(); // it's 10:20:30, i want 10.2030
// ... code which converts the value
}
</script>
...which I can't edit or change them, because they are universal for all of my previous fields. I want add new fields to my page (like myField; see below) and use functions which are not customised specifically for them.
Is it possible to change the format of a returning value? For example...
$("#myField").changeReturningFormat(function(){
// ... code which change format
});
...or change the display format? For example...
$("#myField").val('10.2030'); // a user will see 10:20:30
Check the below sample, you just need to use replace():
var str = "10:20:30";
str = str.replace(/:/, '.');
console.log(str.replace(/:/, ''))
I have the following code in my jsp. I use JSTL ${scheduledRideEndTime} to retrieve the data.
<script>
var timeto2 = ${scheduledRideEndTime};
var hours3 = moment(timeto2).format("hh:mm a")
document.write(hours3);
</script>
If I hit Control Shift F on eclipse the formatting changes to
<script>
var timeto2 = $
{
scheduledRideEndTime
};
var hours3 = moment(timeto2).format("hh:mm a")
document.write(hours3);
</script>
I then get syntax errors in my view. If I redo the code to "${scheduledRideEndTime}"; the Control Shift F does not reformat the code, but view prints Invalid date.
What am I missing here ? I want to be able to reformat code.
Try this:
<script>
var timeto2 = parseInt("${scheduledRideEndTime}");
var hours3 = moment(timeto2).format("hh:mm a")
document.write(hours3);
</script>
I'm trying to use the 'return' value from a JS function as a integer in HTML as follow:
HTML
<span class="..." data-from="..." data-to="<!--I want to use it here!-->" data-speed="..." data-refresh-interval="..."></span>
<!--Print the value here.-->
<div id="daysWorking"></div>
JS
<script>
.
.
document.getElementById("daysWorking").innerHTML = Date.daysBetween(Jan1st2010, today);
</script>
Thanks!
Not sure if I understand it well, but try
var foo = Date.daysBetween(Jan1st2010, today);
document.getElementById("daysWorking").innerHTML = foo;
document.getElementById('mySpan').setAttribute('data-to', foo);
where mySpan is the ID of your span.
If you don't care about old browsers, you can replace the third line of code with
document.getElementById('mySpan').dataset.dataTo = foo;
i have a java script file that it's output is a table with some information.
i want to show this result in one of my DIVs in my page but the result of function,placed at top of my page's Header!
What can i do to fix this?
this is end of my java script file ,in fact this is its output
' document.write("")
document.write(" اوقات شرعی کلیه شهر ها ")
document.write("")
document.write(" ")
document.write(" اذان صبح طلوع خورشید اذان ظهر غروب خورشید اذان مغرب")
document.write(" اوقات به افق : انتخاب شهراراکاردبیلارومیهاصفهاناهوازایلامبجنورد بندرعباسبوشهربیرجندتبریزتهرانخرم آبادرشتزاهدانزنجانساریسمنانسنندجشهرکردشیرازقزوینقمکرمان کرمانشاهگرگانمشهدهمدانیاسوجیزد ")
document.write("") '' and this is its call at the and of my master page '
$(document).ready(function ogh() {
var CurrentDate = new Date();
var JAT = 1;
function pz() { };
init(); document.getElementById("cities").selectedIndex = 12;
coord(); main();
});
$(document).ready(function () {
$("#oghatSharii").append(ogh());
});
</script>
</form>
'
if you could't understand top of my code,,its output is a table
You can set the HTML of the div using jquery in the ready event like follows:
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
....
<script type="text/javascript">
$(document).ready(function () {
$("#myDiv").append(pz());
});
function pz() {
// do here something useful and return the text you want to add to the div
return "Hello there =) !!!";
};
</script>
<div id="myDiv"></div>
Don't forget to install jquery:
https://nuget.org/packages/jQuery
i use this
function ogh()
{
var CurrentDate = new Date();
var JAT = 1;
function pz() { };
init(); document.getElementById("cities").selectedIndex = 12;
coord(); main();
}
$(document).ready(function () {
$("#oghatSharii").append(ogh());
});
but i got an error : one of my functions could't access to oits data
Some steps
Move your JavaScript code at the bottom of the page.
Make use of innerHTML (basic JavaScript) or html() (jQuery) to add so.