I'm new to programming, I'm learning javascript. I don't understand what's wrong with my code but I'm unable to reach the result (i.e. show the total seconds in the text box). The program works fine until matching the pattern. But it's getting all messed up when I'm using the split() function. Please tell me where I'm going wrong. Thank You
<body>
<script>
function cal() {
var text = document.getElementById("pp").innerHTML;
var pattern = text.match(/[0-2][0-9]:[0-5][0-9]:[0-5][0-9]/);
var b = pattern.split(':');
var seconds = (+b[0]) * 3600 + (+b[1]) * 60 + (+b[2]);
document.getElementById("tot").value = seconds;
}
</script>
<div>
<p id="pp">The Time Right Now Is 12:34:56</p>
Total Seconds: <input type=t ext id="tot"><button onclick="cal()"> Click Here!</button>
</div>
</body>
You can check the console (F12 in Chrome) to see if any errors occur. You can also step through the code to see what's going on by adding a debugger; statement there somewhere.
If you move the JavaScript code to a separate file, you can also write tests (for example with Jasmine) to automate testing your code.
All that being said, the following error is displayed in the console:
Uncaught TypeError: pattern.split is not a function
The fix:
var b = pattern[0].split(':');
But once you've started with a Regex, you can continue that way. The following will group the hours, minutes and seconds
var result = "12:34:56".match(/([0-2][0-9]):([0-5][0-9]):([0-5][0-9])/)
var hours = result[1];
var minutes = result[2];
var seconds = result[3];
Better yet, for date parsing like what you are doing here, you could use a library that offers this sort of things out of the box. MomentJS is a very popular one. If this is the only thing you do, using a library is overkill but if you are doing alot of date parsing/formatting, then it will make things much easier for you.
# Install on command line with npm (you can also use bower, ...)
npm install moment
// import and use
import * as moment from "moment";
var parsed = moment("12:34:56", "HH:mm:ss");
String.prototype.split() is a String method, and String.prototype.match() returns an array.
The problem:
You can not applay .split on the returned value from `.match
Solution:
You need to use array index [0] to match the first element from returned array.
Your code after fixing
function cal() {
var text = document.getElementById("pp").innerHTML;
var pattern = text.match(/[0-2][0-9]:[0-5][0-9]:[0-5][0-9]/);
var b = pattern[0].split(':');
var seconds = (+b[0]) * 3600 + (+b[1]) * 60 + (+b[2]);
document.getElementById("tot").value = seconds;
}
<div>
<p id="pp">The Time Right Now Is 12:34:56</p>
Total Seconds: <input type=t ext id="tot">
<button onclick="cal()"> Click Here!</button>
</div>
Pattern return as list. use conditional statement
<body>
<script>
function cal() {
var text = document.getElementById("pp").innerHTML;
var pattern = text.match(/[0-2][0-9]:[0-5][0-9]:[0-5][0-9]/);
b = pattern[0].split(':');
console.log(b)
var seconds = (b[0]) * 3600 + (b[1]) * 60 + (b[2]);
document.getElementById("tot").value = seconds;
}
</script>
<div>
<p id="pp">The Time Right Now Is 12:34:56</p>
Total Seconds: <input type=t ext id="tot"><button onclick="cal()"> Click Here!</button>
</div>
</body>
Related
I am writing the script behind a spreadsheet that has lots of durations on it in the format of (##:##.##) (ex 12:43.76). I need to write some code that converts this to just seconds. I wrote code that did the opposite, made seconds into that format. But when writing a custom formula for this, the .split method does not work.
function MTOS(input){
String(input);
if (typeof(input) != "string") {
Logger.log("Not a string")}
var array = input.split(":");
Logger.log('The original string is: "' + input + '"');
var min = Number(array[0]);
var sec = Number(array[1]);
Logger.log("min=" + min);
Logger.log("sec=" + sec);
var MIN = min*60;
Logger.log(MIN);
var ex = MIN+sec;
Logger.log(ex);
return ex;
}
This is what I have in the script editor. The input is the parameter from the spreadsheet when I write the formula in the sheet itself (ex - =MTOS(3:23.53)). When I run the function in the script editor, it gives me the error "TypeError: Cannot call method "split" of undefined. (line 5, file "MTOS")" and in sheets, it returns "Error : Result was not a number." I understand that this is happening because input is not defined in the function itself, so .split cannot work. But how else can I write the custom formula for sheets?
Thank you.
This seems to work for me: (Perhaps I'm misunderstanding the question).
function MTOS(input){
var iA = input.split(":");
var min = Number(iA[0]);
var sec = Number(iA[1]);
Logger.log('Seconds=%s',min * 60 + sec);
}
I have this line in my html
<td colspan="6" align="right" id="timer"><span>Timer : 50 <span></td>
I am intending to rewrite it into Timer : 60, str.substring to extract only the number 60 (and removing the "Timer : "), then parsing the 60 into a var Countdown (in Jquery)
My Jquery at the moment is
$("#timer").html("Timer : 60")
var str = ("#timer");
var strNum = str.substring(8);
var Countdown = parseInt($("StrNum"));
As you can see I am doing this in seperate steps (but I am not sure if I am correct here too, I am new to these). My question is, am I doing this right, and if is there a way to combine the str.substring and parsing into a single step? Thanks
You should read the basics of jquery. For example this line
var str = ("#timer");
Does absolutely nothing, and so the rest of your script... it should look something like this
var str = $("#timer span").html();
var strNum = str.substr(str.length - 3, 2);
var countdown = parseInt(strNum);
that should work, but you really should read about jquery and javascript
I have been using functions but I am not able to tackle this.
What I have done is created a function, then made this to use the values provided by the document class or ids and do the work. Once work is done then just give the data back! It worked!
Now I want to make this function happen for two divs, the first function works good. The issue is with the second one. The function is correct, their is some other bug while writing the result.
Here is my code:
function time_untilCom(id) {
var Time2 = Date.parse(document.getElementById("time_" + 2).value);
var curTime2 = new Date();
var timeToWrite2 = "";
var seconds2 = Math.floor((curTime2 - Time2) / (1000));
if (seconds2 > 0 && seconds2 < 60) {// seconds..
timeToWrite2 = seconds2 + " seconds ago";
$('#update_' + 2).html(seconds2);
$('#jstime_' + 2).html(timeToWrite2 + " <b>Time that was captured!</b>");
}
}
If I use it as it is, it works! The issue comes when I try to replace these
("time_" + 2), ("#update_" + 2), ("#jstime" + 2) with ("time_" + id), ("#update_" + id), ("#jstime_" + id).
What i want to happen is that the function would be provided with a common ID that is applied throughout the div and use that ID, to get the value of time, convert it to seconds, do other stuff and then provide me with the result in the corresponding element with the id that was in the argument.
function works great, it do provide me with the result. But the issue is with the id its not being sent I guess. Or if is being sent then not being applied. What might be the issue here? And don't mind the seconds i have that covered too.
I am really very sorry for short code:
Pardon me, I was about to write the code for the function too. But electricity ran out!
Here is the code: onload="time_untilCom('2'), this is the way I am executing this.
And once in the main code, it will be executed like this: onload="time_untilCom(#row.Id) because I am using ASP.NET Web Pages I will be using the server side code to write the ID from Database. And will then user the ID throughtout the div to update the time!
From what I understand, you probably want to replace the second line
var Time2 = Date.parse(document.getElementById("time_" + 2).value);
with
var Time2 = Date.parse(document.getElementById(id).value);
And at the end you can also use
$('#'+id).html(timeToWrite2 + " <b>Time that was captured!</b>");
You are passing "id" as an argument, but you never use it inside the function. My question is: In your example you are using 2 as appendix to id attributes. Is it the 2 (or other numbers respectively) that you want to have as the id parameter of the function?
Then you could just replace each + 2 in your code by + id
function time_untilCom(id) {
var Time2 = Date.parse(document.getElementById("time_" + id).value);
var curTime2 = new Date();
var timeToWrite2 = "";
var seconds2 = Math.floor((curTime2 - Time2) / (1000));
if (seconds2 > 0 && seconds2 < 60) {// seconds..
timeToWrite2 = seconds2 + " seconds ago";
$('#update_' + id).html(seconds2);
$('#jstime_' + id).html(timeToWrite2 + " <b>Time that was captured!</b>");
}
}
EDIT: Please tell us where and how exactly do you call time_untilCom? Did you pass the id there?
I'm really new to Javascript and trying to create a form where I'm running into some trouble...
When I use + it does not add up to the value, instead it just puts it back to back. Ex: 5+10 (510)
Here's my code if you want to take a look at it. I'd appreciate any help since I can't figure this out on my own.
var service = document.getElementById("service");
var serviceprice = service.options[service.selectedIndex].id;
var tech = document.getElementById("tech");
var techprice = tech.options[tech.selectedIndex].id;
var hours = document.getElementById("hours").value;
// The error happens here
var total = techprice * hours + serviceprice;
I also have an html part which the script gets the data from.
That happens whenever you have a string rather than a number. The + operator performs concatenation for strings. Make sure you parse your strings to numbers using parseFloat or parseInt:
var service = document.getElementById("service");
var serviceprice = parseInt(service.options[service.selectedIndex].id, 10);
var tech = document.getElementById("tech");
var techprice = parseInt(tech.options[tech.selectedIndex].id, 10);
var hours = parseInt(document.getElementById("hours").value, 10);
Note that parseInt takes an argument to specify the base. You almost always want base 10.
Try changing this line:
var total = techprice * hours + serviceprice;
to
var total = techprice * hours + parseFloat(serviceprice);
I suspect 'servicePrice' is a string, and it will then try to concatenate the first value (let's say: 100) with the second value (which is, not a number, but a string, let's say 'test'), the result being '100test'.
Try to convert the string to int first with parseInt or to float with parseFloat
This is not especially elegant, but I find it simple, easy, and useful:
var total = -(-techprice * hours - serviceprice);
or even:
var total = techprice * hours -(-serviceprice);
They both eliminate the ambiguous + operator.
I want change following javascript code to jquery code, How is it?
With done change hourOffset in date 3, 21 and 9, 22.
DEMO: http://jsfiddle.net/zJRDC/
<script type="text/javascript">
var interval = self.setInterval("clock()", 1000);
function clock() {
var date = new Date();
var hourOffset = 3;
date.setUTCHours(date.getUTCHours(), date.getUTCMinutes());
var time = date.getTime();
date.setUTCFullYear(date.getUTCFullYear(), 3, 21);
var dstStart = date.getTime();
date.setUTCFullYear(date.getUTCFullYear(), 9, 22);
var dstEnd = date.getTime();
if (time > dstStart && time < dstEnd){ hourOffset = 4;}
date.setUTCHours(date.getUTCHours() + hourOffset, date.getUTCMinutes() + 30);
var output = date.getUTCHours() + ":" + date.getUTCMinutes() + ":" + date.getUTCSeconds();
document.getElementById("clock").innerHTML = output
}
</script>
<div id="clock"></div>
There's precisely one line of that where jQuery might apply:
document.getElementById("clock").innerHTML = output
which with jQuery could be
$("#clock").html(output);
That uses $ to look up the element, which includes a workaround for a bug in getElementById in earlier versions of IE, and then uses the html method to set the markup on the element (which is very like setting innerHTML — again, though, with some workarounds for problematic bits in some cases; they probably don't apply to this specific code).
Note that jQuery is just a framework written in JavaScript. It smooths over some browser differences dealing with the DOM, and provides a lot of handy utility functionality, but it's not a thing separate from JavaScript. You write JavaScript code, and you optionally use jQuery in it (just like any other library).
if your code works. you don't really need jquery. unless you want to create re-usable function or your custom plugin.
a quick sample to use clock() as jquery plugins (didn't test)
(function( $ ){
$.fn.myClock = function(timeout) {
var interval = setInterval("clock()", timeout);
function clock() {
//..calculate date output
var output = //...
this.html(output)
}
};
})( jQuery );
then to use your plugin
$(document).ready(function(){
$('#clock').myClock(1000);
}
see Plugins/Authoring and learn-how-to-create-your-own-jquery-plugin
JQuery is already done with JavaScript . Nothing to convert because JQuery is not a language ;).