calculating time wit dynamic input - javascript

I have this script
<input type="hidden" id="from_t" value="<?= date('H:i',strtotime($row['from_t'])) ?>">
<input style="width: 50px" type="number" id="h" min="0" class="trvael">
$(document).on('change','.trvael',function () {
var form_t = $('#from_t').val(); // 10:00
var total_time = 5;
var travel_h = $('#h').val(); //user dynamic input
var sum = form_t - (parseFloat(total_time) + parseFloat(travel_h)) ;
})
How can I claculate all the values and get new time.
For example :
10:00 - 5 - 2.5 = 02:30
Thank you!

You can try something like this.
var from_t = '10:00'
var value1 = '5';
var value2 = '2.5';
var date = new Date();
var splits = from_t.split(':');
date.setHours(splits[0]);
date.setMinutes(splits[1]);
date.setMinutes(date.getMinutes() - ((+value1) + (+value2)) * 60);
console.log(date.getHours() + ':' + date.getMinutes());

I'm pretty sure you want something like my DateTime constructor to handle the job. I've already created this, so:
//<![CDATA[
/* js/external.js */
function DateTime(dateElement, timeElement, dateInstance){
var t = this;
this.dateElement = dateElement; this.timeElement = timeElement;
this.date = dateInstance instanceof Date ? dateInstance : new Date;
this.dateValue = function(dateInstance){
if(dateInstance instanceof Date)this.date = dateInstance;
var dt = this.date;
return dt.getFullYear()+'-'+(dt.getMonth()+1).toString().replace(/^(\d)$/, '0$1')+'-'+dt.getDate().toString().replace(/^(\d)$/, '0$1');
}
this.showDate = function(dateInstance){
this.dateElement.value = this.dateValue(dateInstance);
return this;
}
this.timeValue = function(dateInstance){
if(dateInstance instanceof Date)this.date = dateInstance;
var dt = this.date;
return dt.getHours().toString().replace(/^(\d)$/, '0$1')+':'+dt.getMinutes().toString().replace(/^(\d)$/, '0$1');
}
this.showTime = function(dateInstance){
this.timeElement.value = this.timeValue(dateInstance);
return this;
}
this.showDate().showTime();
this.dateChange = function(changeFunc, noTimeFunc){
this.dateElement.oninput = function(){
var v = this.value, s = t.timeElement.value;
if(v === '')v = this.value = t.dateValue(noTimeFunc(t));
if(s === '')s = t.timeValue(this.date);
t.date = new Date(v+' '+s); changeFunc(t.date, t);
}
return this;
}
this.timeChange = function(changeFunc, noTimeFunc){
this.timeElement.oninput = function(){
var v = this.value, s = t.dateElement.value;
if(v === '')v = this.value = t.timeValue(noTimeFunc(t));
if(s === '')s = t.dateValue(this.date);
t.date = new Date(s+' '+v); changeFunc(t.date, t);
}
return this;
}
}
$(function(){ // jQuery load
var dt = new DateTime($('#date')[0], $('#time')[0]);
function consoleIt(dateInstance){
console.log('display of dt.date --> '+dateInstance.toString());
console.log('dt.date for server --> '+dateInstance.getTime());
}
consoleIt(dt.date);
dt.dateChange(function(r){
consoleIt(r);
}).timeChange(function(a){
consoleIt(a);
});
}); // end load
//]]>
/* css/external.css */
*{
box-sizing:border-box; padding:0; margin:0;
}
html,body{
width:100%; height:100%;
}
body{
background:#ccc;
}
#content{
padding:7px;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale:1' />
<title>Test Template</title>
<link type='text/css' rel='stylesheet' href='css/external.css' />
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<script type='text/javascript' src='js/external.js'></script>
</head>
<body>
<div id='content'>
<input id='date' type='date' value=''/><input id='time' type='time' value='' />
</div>
</body>
</html>
Of course, you could use jQuery DatePicker, but that doesn't do time.
If you add another Date instance argument to DateTime you can set the default.

Related

newbie to js. how do i ask user for input with function

Improved hello
Complete the following program so that it asks the user for his first and last names, then show the result of the sayHello() function.
// Say hello to the user
function sayHello(firstName, lastName) {
const message = `Hello, ${firstName} ${lastName}!`;
return message;
}
// TODO: ask user for first and last name
// TODO: call sayHello() and show its result
Although I've omitted your template literals from my answer (for compatibility reasons). This should show you some basic JavaScript.
//<![CDATA[
/* external.js */
var doc, bod, htm, M, I, S, Q, old = onload; // for use on other loads
onload = function(){
if(old)old(); // change old var name if using technique on other pages
doc = document; bod = doc.body; htm = doc.documentElement;
M = function(tag){
return doc.createElement(tag);
}
I = function(id){
return doc.getElementById(id);
}
S = function(selector, within){
var w = within || doc;
return w.querySelector(selector);
}
Q = function(selector, within){
var w = within || doc;
return w.querySelectorAll(selector);
}
I('f').onsubmit = function(){
return false;
}
var first = I('first'), last = I('last'), show = I('show'), out = I('out');
show.onclick = function(){
out.innerHTML = first.value+' '+last.value; first.value = last.value = '';
}
}
//]]>
/* external.css */
html,body{
padding:0; margin:0;
}
body{
background:#000; overflow-y:scroll;
}
.main{
width:940px; background:#ccc; padding:20px; margin:0 auto;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<meta name='viewport' content='width=device-width' />
<title>Test Template</title>
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<form id='f' name='f'>
<input id='first' name='first' type='text' placeholder='First Name' />
<input id='last' name='last' type='text' class='empty' placeholder='Last Name' />
<input id='show' name='show' type='button' value='Display Input' />
</form>
<div id='out'></div>
</div>
</body>
</html>
function askForName() {
var person = prompt("Please enter your first and last name:");
if (person !== null) {
var firstName = person.split(' ')[0];
var lastName = person.split(' ')[1];
console.log(sayHello(firstName, lastName));
}
}
function sayHello(firstName, lastName) {
const message = `Hello, ${firstName} ${lastName}!`;
return message;
}
askForName();
The result will be logged to your console.

Javascript SetInterval and get value Math.random

I have just created random number. My problems is how to get value random in id and how to set price changes automatically every 5 seconds and the fluctuation amplitude less than +/- 5% compared to the current, I don't know use the setinterval function everybody help me
My code Random Price :
function generateRandomNumber(min,max) {
return (Math.random() * (max - min) + min).toFixed(2);
};
document.getElementById('price1').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price2').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price3').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price4').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price5').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price6').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price7').innerHTML = generateRandomNumber(0,99.99);
It took me a while to work around the recursion issues I was running into, before I came up with a better solution.
//<![CDATA[
// external.js
function RandNumMaker(min, max, withinPercent, secondsInterval, decimalPlaces){
this.withinPercent = withinPercent || 5;
this.secondsInterval = secondsInterval || 5;
this.decimalPlaces;
if(decimalPlaces){
this.decimalPlaces = decimalPlaces;
}
var t = this, ia = [];
function rb(mn, mx){
return mx-Math.random()*(mx-mn);
}
var pn = rb(min, max);
function rn(){
var p = 1;
if(Math.floor(Math.random()*2) === 1)p = -1
return p*(Math.floor(Math.random()*t.withinPercent)+1)/100*pn;
}
function rf(){
var r, d = t.decimalPlaces;
pn += rn();
if(pn < min || pn > max){
return rf();
}
r = pn;
if(d)r = (Math.floor(Math.round(Math.pow(10, d+1)*r)/10)/Math.pow(10, d)).toFixed(d);
return r;
}
this.setDiv = function(div){
div.innerHTML = rf(); ia = [];
var iv = setInterval(function(){
div.innerHTML = rf();
}, this.secondsInterval*1000);
ia.push(iv);
return this;
}
this.stop = function(){
for(var i=0,l=ia.length; i<l; i++){
if(ia[i]){
clearInterval(ia[i]);
}
}
ia = [];
return this;
}
}
var doc, bod, C, E, N, old = onload; // for use on other loads
onload = function(){
if(old)old();
doc = document; bod = doc.body;
C = function(tag){
return doc.createElement(tag);
}
E = function(id){
return doc.getElementById(id);
}
N = function(className, inElement){
var ii = inElement || doc;
var cN = ii.getElementsByClassName(className);
if(cN){
return cN;
}
var tn = ii.getElementsByTagName('*');
for(var i=0,e,a=[],l=tn.length; i<l; i++){
e = tn[i];
if(e.className && e.className === className)a.push(e);
}
return a;
}
var sr = new RandNumMaker(0, 99.99), sl = N('slow');
var fr = new RandNumMaker(0, 99.99), fs = N('fast');
sr.decimalPlaces = 2;
fr.secondsInterval = 0.1; fr.withinPercent = 5;
for(var i=0,l=sl.length; i<l; i++){
sr.setDiv(sl[i]);
}
for(var i=0,l=fs.length; i<l; i++){
fr.setDiv(fs[i]);
}
}
//]]>
/* extrnal.js */
html,body{
padding:0; margin:0;
}
body{
background:#000; overflow-y:scroll;
}
.main{
width:940px; background:#fff; padding:20px; margin:0 auto;
}
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<meta name='viewport' content='width=device-width' />
<title>test</title>
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<div class='slow'></div>
<hr />
<div class='fast'></div>
<div class='fast'></div>
<div class='fast'></div>
<div class='fast'></div>
</div>
</body>
</html>
Should work now!
After you create a new RandNumMaker(min, max) then you can set randomNumMarkerInstance.decimalPlaces, randomNumMakerInstance.withinPercent and randomNumMakerInstance.secondsInterval using simple assignment. randomNumMakerInstance.setDiv(div) starts it. randomNumMakerInstance.stop() stops it.
I think you can understand this code.
I tried to keep your code.
The key is to use setInterval function.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<script>
function generateRandomNumber(min,max) {
return (Math.random() * (max - min) + min).toFixed(2);
};
function assignData(){
document.getElementById('price1').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price2').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price3').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price4').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price5').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price6').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price7').innerHTML = generateRandomNumber(0,99.99);
setInterval(assignData, 5000); //every 5 seconds
}
</script>
<body onload="assignData()">
<h2 id="price1"></h2>
<h2 id="price2"></h2>
<h2 id="price3"></h2>
<h2 id="price4"></h2>
<h2 id="price5"></h2>
<h2 id="price6"></h2>
<h2 id="price7"></h2>
</body>
</html>
My interpretation of your question: all elements to start with a random value between 0 and 99.99, and then every five seconds one randomly selected element is to be updated, changing its value by a random amount within 5% of its current value. (If you want to update every element every five seconds then change the random selection to be a loop instead.)
For simplicity in the demo snippet (click "Run code snippet" to see it work), I've used a group of <li> elements which I select with .querySelectorAll("li"), but if you really want to do it using element IDs you could say .querySelectorAll("#price1,#price2,#price3,#price4,#price5,#price6,#price7").
function generateRandomNumber(min,max) {
return (Math.random() * (max - min) + min).toFixed(2);
}
// get list of elements:
var elements = document.querySelectorAll("li");
// populate all elements initially:
[].forEach.call(elements, function(el) {
el.innerHTML = generateRandomNumber(0,99.99);
});
// update an element at random every second:
setInterval(function update() {
var element = elements[Math.floor(Math.random() * elements.length)];
var currentVal = +element.innerHTML;
element.innerHTML = generateRandomNumber(currentVal * 0.95, currentVal * 1.05);
}, 1000);
<ul>
<li></li><li></li><li></li><li></li><li></li><li></li><li></li>
</ul>
Note that five second intervals seemed too slow for a demo, so I've used one second (1000ms) here.
Further reading:
.querySelectorAll()
Array .forEach() method
Function.prorotype.call()
Math.floor()
unary plus operator
Hope this will help.
<body>
<p id="price1"></p>
<p id="price2"></p>
<p id="price3"></p>
<p id="price4"></p>
<p id="price5"></p>
<p id="price6"></p>
<p id="price7"></p>
</body>
<script>
//set initial random number for the elements
document.getElementById('price1').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price2').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price3').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price4').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price5').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price6').innerHTML = generateRandomNumber(0,99.99);
document.getElementById('price7').innerHTML = generateRandomNumber(0,99.99);
//set random number to elements with fluctuation +/- 5%
setRandomToElements()
function generateRandomNumber(min,max) {
return (Math.random() * (max - min) + min).toFixed(2);
};
function setRandomToElements(){
//get current prices
var currentPrice1 = parseInt(document.getElementById('price1').innerHTML);
var currentPrice2 = parseInt(document.getElementById('price2').innerHTML);
var currentPrice3 = parseInt(document.getElementById('price3').innerHTML);
var currentPrice4 = parseInt(document.getElementById('price4').innerHTML);
var currentPrice5 = parseInt(document.getElementById('price5').innerHTML);
var currentPrice6 = parseInt(document.getElementById('price6').innerHTML);
var currentPrice7 = parseInt(document.getElementById('price7').innerHTML);
var fluctuation = 0.05;//5%
//random new numbers +/-5% current price
document.getElementById('price1').innerHTML = generateRandomNumber(currentPrice1-(currentPrice1*fluctuation), currentPrice1+(currentPrice1*fluctuation));
document.getElementById('price2').innerHTML = generateRandomNumber(currentPrice2-(currentPrice2*fluctuation), currentPrice2+(currentPrice2*fluctuation));
document.getElementById('price3').innerHTML = generateRandomNumber(currentPrice3-(currentPrice3*fluctuation), currentPrice3+(currentPrice3*fluctuation));
document.getElementById('price4').innerHTML = generateRandomNumber(currentPrice4-(currentPrice4*fluctuation), currentPrice4+(currentPrice4*fluctuation));
document.getElementById('price5').innerHTML = generateRandomNumber(currentPrice5-(currentPrice5*fluctuation), currentPrice5+(currentPrice5*fluctuation));
document.getElementById('price6').innerHTML = generateRandomNumber(currentPrice6-(currentPrice6*fluctuation), currentPrice6+(currentPrice6*fluctuation));
document.getElementById('price7').innerHTML = generateRandomNumber(currentPrice7-(currentPrice7*fluctuation), currentPrice7+(currentPrice7*fluctuation));
setInterval(setRandomToElements, 5000);
}
</script>
Fiddle

JQuery slider for showing date interval

I am trying to show appropriate date according to slider position.This slider runs automatically till the end and shows what is the current date. So, problem is when i slide it back is not showing appropriate date. Any help please?
Here is the full code!
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Slider - Default functionality</title>
<link rel="stylesheet" href="css/jquery-ui.css">
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/jquery-ui.js"></script>
<script>
var i = 1, k = 1;
var isPaused = false;
var eventNum=0;
var inter;
var ar = [];
function startSlider(interval, seconds)
{
var seconds = seconds*1000;
var tmp = interval;
var st = Math.ceil(1000/interval);
inter = setInterval(function()
{
$( "#slider" ).slider(
{
range: "min",
max:1000,
slide: function()
{
if (isPaused)
{
i=$(this).slider("value")+1;
}
else
{
alert("Pause to slide!");
}
}
});
if(!isPaused)
{
if(k%st == 0)
{
setDate(++eventNum);
ar[eventNum] = $("#slider").slider("value");
k = 1;
if (eventNum==interval)
{
clearInterval(inter);
while(i!=1000){
$("#slider").slider("value",i++);
}
}
}
k++;
$("#slider").slider("value",i++);
}
},seconds/st);
}
function pause(){
isPaused = true;
}
function play(){
clearInterval(inter);
var d1 = document.getElementById("date1").value;
document.getElementById("date").value = d1;
startSlider(dateDifference(), document.getElementById("time").value);
isPaused = false;
}
function stop(){
eventNum = 0;
i = 0;
clearInterval(inter);
var d1 = document.getElementById("date1").value;
document.getElementById("date").value = d1;
$("#slider").slider("value",0);
}
function set(){
i=$("#slider").slider("value")+1;
$("#slider").slider("value",i++);
}
function dateDifference(){
var d1 = new Date(document.getElementById("date1").value);
var d2 = new Date(document.getElementById("date2").value);
var timeDiff = Math.abs(d2.getTime() - d1.getTime());
return difDays = Math.ceil(timeDiff/(1000*3600*24));
}
function setDate(n){
var d1 = new Date(document.getElementById("date1").value);
d1.setDate(d1.getDate() + n);
var d2 = d1.toISOString().substr(0,10);
document.getElementById("date").value = d2;
}
$(function() {
$("#date1").on("change",function(){
var selected = $(this).val();
document.getElementById("date2").setAttribute("min",selected);
});
});
$("slider").mouseup(function(){
$(this).after("Mouse button released.");
});
</script>
</head>
<body>
<div>
<label for="from">From</label>
<input type="date" name="date1" id="date1" >
<label for="to">to</label>
<input type="date" name="date2" id="date2" min="">
<label for="time">Time</label>
<input type="text" name="time" id="time">
<input type="text" name="date" id="date">
</div>
<br>
<div id="slider" ></div>
<br>
<button onclick="pause()">pause</button>
<button onclick="play()">play</button>
<button onclick="stop()">stop</button>
</body>
</html>

Including created javascript files in html

Somehow I can't create external javascript files. If I import them from other examples, they work fine but if it is files I create and import them, they don't work. They are working fine if I inclued them into the html but if I reference them they don't work. I don't know what I am doing wrong.
Here's my html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Documento sem título</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.ui.draggable.js" type="text/javascript"></script>
<!-- Core files -->
<script src="jquery.alerts.js" type="text/javascript"></script>
<body>
<script type="text/javascript" src="horario.js"></script>
<div id="entrada">
<input id="time" class="inputs" type="text" maxlength="2"></input>
<input id="time2" class="inputs" type="text" maxlength="2"></input>
<button class="inputs" id="confirm_button" class="inputs1" onKeyPress="localStore()" onClick="localStore()">entrada</button>
</div>
<div id="result"></div>
<div id="millsentr"></div>
<div id="millssai"></div>
<div id="mills"></div>
<div id="totHoras"></div>
</body>
</html>
And here's the javascript file:
$(".inputs").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('.inputs').focus();
}
});
$(".inputs1").keyup(function () {
if (this.value.length == this.maxLength) {
$(this).next('.inputs').focus();
}
});
$(document).ready( function() {
$("#confirm_button").click( function() {
jConfirm('Can you confirm this? ', 'Confirmation Dialog', function(r) {
var entradasaida = 0;
entradasaida = localStorage.getItem("entradasaida");
if(r == true){
if(entradasaida == 0){
var time = $('#time').val();
var time2 = $('#time2').val();
var datetime = new Date();
var year = datetime.getFullYear();
var month = datetime.getMonth()+1;
if(month < 10){
month = "0"+month
}
var day = datetime.getDay()+1;
if(day < 10){
day = "0"+day
}
var date = new Date(year+"-"+month+"-"+day+" "+time+":"+time2);
var mills = date.getTime();
localStorage.setItem("horas", time);
localStorage.setItem("mins", time2);
localStorage.setItem("entradasaida",1);
localStorage.setItem("millsEnt",mills);
$('#confirm_button').text("Saida");
$('#time, #time2').val("");
$('#millsentr').text(mills);
} else{
var horasEnt = localStorage.getItem("horas");
var minsEnt = localStorage.getItem("mins");
var entrada = localStorage.getItem("millsEnt");
localStorage.setItem("entradasaida",0);
$('#confirm_button').text("Entrada");
var time = $('#time').val();
var time2 = $('#time2').val();
var datetime = new Date();
var year = datetime.getFullYear();
var month = datetime.getMonth()+1;
if(month < 10){
month = "0"+month
}
var day = datetime.getDay()+1;
if(day < 10){
day = "0"+day
}
var date1 = new Date(year+"-"+month+"-"+day+" "+time+":"+time2);
var millssai = date1.getTime();
$('#millssai').text(millssai);
var totMills = (millssai - entrada)
var horas = time - horasEnt;
var mins = time2 - minsEnt;
if(mins < 0){
mins = mins*(-1);
horas = horas-1;
}
var totHoras = horas+":"+mins
$('#totHoras').text(totHoras);
$('#mills').text(totMills);
$('#time, #time2').val("");
}
} else{r == false}
});
});
});
In this, the horario.js is the file I created and is not working, the other script files I used from examples are working ok.

How to I retrieve a current value of textarea ? which method instead of $("form").submit(function(){ can be used?

This is my code:
<html>
<head>
<title>Perl WEB</title>
<script type="text/javascript" src="/Perl1/codemirror.js"></script>
<link rel="stylesheet" href="/Perl1/codemirror.css"/>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="http://code.guru99.com/perl/perl.js"></script>
<style>
.CodeMirror {
border: 1px solid #eee;
}
.CodeMirror-scroll {
height: auto;
overflow-y: hidden;
overflow-x: auto;
}
</style>
<script>
$(document).ready(function(){
$("form").submit(function(){
alert("Submitted");
});
});
</script>
<script type="text/javascript">
function execute() {
p5pkg.CORE.print = function(List__) {
var i;
for (i = 0; i < List__.length; i++) {
document.getElementById('print-result').value += p5str(List__[i])
}
return true;
};
p5pkg.CORE.warn = function(List__) {
var i;
List__.push("\n");
for (i = 0; i < List__.length; i++) {
document.getElementById('log-result').value += p5str(List__[i]);
}
return true;
};
p5pkg["main"]["v_^O"] = "browser";
p5pkg["main"]["Hash_INC"]["Perlito5/strict.pm"] = "Perlito5/strict.pm";
p5pkg["main"]["Hash_INC"]["Perlito5/warnings.pm"] = "Perlito5/warnings.pm";
var source = document.getElementById('source').value;
alert(source);
var pos = 0;
var ast;
var match;
document.getElementById('log-result').value = "";
// document.getElementById('js-result').value = "";
document.getElementById('print-result').value = "";
try {
// compile
document.getElementById('log-result').value += "Compiling.\n";
var start = new Date().getTime();
var js_source = p5pkg["Perlito5"].compile_p5_to_js([source]);
var end = new Date().getTime();
var time = end - start;
document.getElementById('log-result').value += "Compilation time: " + time + "ms\n";
// document.getElementById('js-result').value += js_source + ";\n";
// run
start = new Date().getTime();
eval(js_source);
end = new Date().getTime();
time = end - start;
document.getElementById('log-result').value += "Running time: " + time + "ms\n";
p5pkg.CORE.print(["\nDone.\n"]);
}
catch(err) {
document.getElementById('log-result').value += "Error:\n";
document.getElementById('log-result').value += err + "\n";
document.getElementById('log-result').value += "Compilation aborted.\n";
}
}
</script>
</head>
<body>
<form>
<textarea id="source" cols="70" rows="10">
say 'h';
</textarea>
<div class="hint">This code is editable. Click Run to execute.</div>
<input type="button" value="Run" onclick="execute()"/></br>
Output:</br>
<textarea id="print-result" disabled="true" rows="10" cols="70"></textarea></br>
Log:</br>
<textarea id="log-result" disabled="true" cols="70"></textarea>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("source"), {
lineNumbers: true,
indentUnit: 4,
indentWithTabs: true,
enterMode: "keep",
tabMode: "shift"
});
</script>
</form>
</body>
</html>
problem : so I have alert the value of text area by:
var source = document.getElementById('source').value;
alert(source);
but the value of text area is alert is load at the time of page load.and I want to alert current value of textarea.
I have also tried this:
$("form").submit(function())
but that also not useful.
How can I do this?
you can use
$("#source").val();
Try to use
$("#source").val() to get value of textarea
Thanks
I suppose your problem might be occuring because of the Editor you are using.
http://codemirror.net/doc/manual.html
You should be able to retrieve the value with:
editor.getValue()

Categories