javascript check for specific characters - javascript

I am trying to create a timer in javascript, and I have got it working, however I am trying to validate the users input, for the time. Currently it will accept anything as long as the inputbox is not empty. But I am wanting to only allow numbers, colon (:) and periods (.), I have looked at several questions, but most seem to be only checking for all text characters.
Here is the working code: https://jsfiddle.net/hLqayL1w/
OR
HTML:
<div class="maincont">
<h2>Please enter a amount of time</h2>
<p id="timer">0:00</p>
<div class="container">
<input id="request" type="text" placeholder="Time">
<button type="submit" class="click">Start timer</button>
</div>
<P id="cancelbutton" class="cancel">Cancel timer</P>
</div>
JS:
$(document).ready(function() {
$('#cancelbutton').hide();
});
$('.click').click(function() {
var conts = $('#request').val();
if ($('#request').val() === "") {
return;
}
$('.container').hide();
$('#cancelbutton').fadeIn('slow');
var rawAmount = $('#request').val();
var cleanAmount = rawAmount.split(':');
var totalAmount = parseInt(cleanAmount[0] | 0) * 60 + parseInt(cleanAmount[1] | 0);
$('#request').val(" ");
var loop, theFunction = function() {
totalAmount--;
if (totalAmount == 0) {
clearInterval(loop);
$('#cancelbutton').hide();
$('.container').fadeIn('slow');
}
var minutes = parseInt(totalAmount / 60);
var seconds = parseInt(totalAmount % 60);
if (seconds < 10)
seconds = "0" + seconds;
$('#timer').text(minutes + ":" + seconds);
$('#cancelbutton').click(function() {
totalAmount = 1
});
};
var loop = setInterval(theFunction, 1000);
})

In your example you just check if the input is an empty string lets change that so we check if it matches an regular expression:
if (!$('#request').val().match(/[0-9:.]/gi)) {
return;
}
We make it look for numbers,colons and dots everything else will not match and the return will run.
Here is an working example.
(This is just an quick and dirty example it is not showcasing that the regex should be written in this way, there probably are better ways to write this)

How about this?
$('#request').keyup(function() {
var el = $(this),
val = el.val();
el.val(val.replace(/[^\d\:.]/gi, ""));
}).blur(function() {
$(this).keyup();
});
It will check check if the input is number/./:, if not it will remove it live.
$(document).ready(function() {
$('#cancelbutton').hide();
});
$('#request').keyup(function() {
var el = $(this),
val = el.val();
el.val(val.replace(/[^\d\:.]/gi, ""));
}).blur(function() {
$(this).keyup();
});
$('.click').click(function() {
var conts = $('#request').val();
if ($('#request').val() === "") {
return;
}
$('.container').hide();
$('#cancelbutton').fadeIn('slow');
var rawAmount = $('#request').val();
var cleanAmount = rawAmount.split(':');
var totalAmount = parseInt(cleanAmount[0] | 0) * 60 + parseInt(cleanAmount[1] | 0);
$('#request').val(" ");
var loop, theFunction = function() {
totalAmount--;
if (totalAmount == 0) {
clearInterval(loop);
$('#cancelbutton').hide();
$('.container').fadeIn('slow');
}
var minutes = parseInt(totalAmount / 60);
var seconds = parseInt(totalAmount % 60);
if (seconds < 10)
seconds = "0" + seconds;
$('#timer').text(minutes + ":" + seconds);
$('#cancelbutton').click(function() {
totalAmount = 1
});
};
var loop = setInterval(theFunction, 1000);
})

Related

Add value from textbox to counter

I'm learning javascript and I want to create a simple clock. I want for user to be able to change minutes by entering a number in textbox and pressing a button, so when that number is displayed and when the seconds are counted to 60, that displayed number increase by 1, my code won't work, help pls:
var seconds = 0;
var minutes2 = 0;
var rezultat;
let dugme = document.querySelector("#dugme");
var el = document.getElementById("seconds-counter");
var el2 = document.getElementById("minutes-counter");
function incrementSeconds() {
seconds += 1;
if (seconds === 60) {
return seconds = 0;
}
el.innerText = seconds;
}
var cancel = setInterval(incrementSeconds, 1000);
dugme.addEventListener("click", function() {
var minutes = parseInt(document.querySelector("#value").value);
el2.innerText = minutes;
})
function incrementMinutes() {
minutes2 += 1;
if (minutes2 === 60) {
return minutes2 = 0;
}
rezultat = (seconds + minutes2 + minutes);
el2.innerText = rezultat;
}
var cancel = setInterval(incrementMinutes, 60000);
<form>
<input type="text" id="value">
<button id="dugme" type="button">minuti</button>
</form>
<div id="seconds-counter"></div>
<div id="minutes-counter"></div>
</form>
You have a few problems in your code. The main mistake is that your variable minutes is not defined in the function incrementMinutes() where you are trying to use it. You have to calculate it again.
Other improvements that you can make are:
Remove the return in your incrementSeconds and incrementMinutes function
Have only 1 setInterval, and call incrementMinutes when seconds reach 60.
You can see a snippet here below:
var seconds = 0;
var minutes2 = 0;
var rezultat;
let dugme = document.querySelector("#dugme");
var el = document.getElementById("seconds-counter");
var el2 = document.getElementById("minutes-counter");
function incrementSeconds() {
seconds += 1;
if (seconds === 60) {
seconds = 0;
incrementMinutes();
}
el.innerText = seconds;
}
var cancel = setInterval(incrementSeconds, 1000);
dugme.addEventListener("click", function() {
var minutes = parseInt(document.querySelector("#value").value);
el2.innerText = minutes;
})
function incrementMinutes() {
minutes2 += 1;
if (minutes2 === 60) {
minutes2 = 0;
}
rezultat = (minutes2 + parseInt(document.querySelector("#value").value));
el2.innerText = rezultat;
}
<form>
<input type="text" id="value">
<button id="dugme" type="button">minuti</button>
</form>
<div id="seconds-counter"></div>
<div id="minutes-counter"></div>
To show here the behavior I made a minute to 5 seconds.
As a formatting improvement, if you want to show in result min:sec you can do this
min = min < 10 ? "0"+min : min;
seconds = seconds < 10 ? "0" + seconds : seconds;
To build the string with leading zeros.
I have removed the returns because they were not neccessary you can inside reset the value there is no need to return it.
var seconds = 0;
var min = 0;
var rezultat;
let dugme = document.querySelector("#dugme");
var secCounter = document.getElementById("seconds-counter");
var mintCounter = document.getElementById("minutes-counter");
function incrementSeconds() {
seconds += 1;
if (seconds === 60) {
seconds = 0;
}
secCounter.innerText = seconds;
}
var cancel = setInterval(incrementSeconds, 1000);
function incrementMinutes() {
min += 1;
if (min === 60) {
min = 0;
}
tempMin = min;
tempSec = seconds;
min = min < 10 ? "0"+min : min;
seconds = seconds < 10 ? "0" + seconds : seconds;
rezultat = (min+":"+seconds);
mintCounter.innerText = rezultat;
min = tempMin;
seconds = tempSec;
}
// for debugging to 5 sec
var cancel = setInterval(incrementMinutes, 5000);
dugme.addEventListener("click", function() {
var inpMinutes = parseInt(document.querySelector("#value").value);
min = inpMinutes;
mintCounter.innerText = min;
})
<form>
<input type="text" id="value">
<button id="dugme" type="button">minuti</button>
</form>
<div id="seconds-counter"></div>
<div id="minutes-counter"></div>
</form>

storing user input as var

So this is a timer that computes orders per hour. when i hard code the orders everything works the way i want it. but i can't seem to figure how to get user input to set the amount of orders. this is what I've been trying and it is not working. any ideas??
<html>
<body>
<p><strong>Time Elapsed:</strong><span id="time-elapsed"</span></p>
<button onclick="openFunc()">Start Time</button>
<button onclick="myStopFunction()">Stop time</button><br><br>
<input type="text" id="orderAmount"><br>Enter Number of Orders</input><br><br>
<button onclick="calculate(timeElapsed, orders)">Calculate...</button>
<script>
var timeElapsed = 0;
var myVar = '';
var average = 0;
var orders = document.getElementById("orderAmount").innerHTML += orders;
function openFunc(){
start();
}
function calculate(time, _orders) {
var avg = _orders/(time/_orders);
if (avg<1){
avg = 1;
}
document.write(avg + " Bags per Hour");
}
function start() {
if ( myVar != "" ) {
console.log('timer is running');
return;
}
clearInterval(myVar);
myVar = setInterval(function(){
myTimer()
}, 1000);
}
function myTimer() {
timeElapsed += 1;
document.getElementById("time-elapsed").innerHTML = formatTime(timeElapsed);
}
function formatTime(time) {
var hours = formatNumber(Math.floor(time/3600))
var minutes = formatNumber(Math.floor(time/60));
var seconds = formatNumber(time%60);
//console.log('minutes: ', minutes);
//console.log('seconds: ', seconds);
return hours + ":" + minutes + ":" + seconds
}
function formatNumber(number) {
if ( number < 10 ) {
return 0 + '' + number
}
return number
}
function myStopFunction() {
clearInterval(myVar);
myVar = "";
}
</script>
</body>
</html>
This is how you get user input from text field with orderAmount id:
var orders = document.getElementById("orderAmount").value;

Can't get form to hide in JS

Having this problem with trying to get a form to hide in Javascript.
Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<title>Timer</title>
<link rel="stylesheet" href="style.css">
<script src="javascript.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Roboto:400,300' rel='stylesheet' type='text/css'>
</head>
<body>
<div id="wrapper">
<div id="time">00:00:00</div>
<form id="myform">
<input type="text" autocomplete="off" id="box" placeholder="00:00:00" onkeypress="checkBox(event)">
</form>
</div>
</body>
</html>
And here is my JS:
function timer(time) {
document.getElementById("myform").style.display = "none";
document.getElementById("time").style.display = "inline";
var interval = setInterval(function () {
if (time == 0) {
time = 299;
} else {
var newTime = timeFormat(time);
document.getElementById("time").innerHTML = newTime;
document.title = newTime;
time--;
}
}, 1000);
}
function checkBox(event) {
if (event.keyCode == 13) {
var string = document.getElementById("box").value;
var numTest = string;
if (string.length != 0) {
var numOfColons = string.split(":").length - 1;
var hr = 0;
var min = 0;
var sec = 0;
if (numOfColons == 2) {
numTest = numTest.replace(":", "");
numTest = numTest.replace(":", "");
hr = string.substring(0, string.indexOf(":"));
string = string.replace(string.substring(0, string.indexOf(":")+1), "");
min = string.substring(0, string.indexOf(":"));
string = string.replace(string.substring(0, string.indexOf(":")+1), "");
sec = string.substring(0, string.length);
} else if (numOfColons == 1) {
numTest = numTest.replace(":", "");
min = string.substring(0, string.indexOf(":"));
string = string.replace(string.substring(0, string.indexOf(":")+1), "");
sec = string.substring(0, string.length);
} else if (numOfColons == 0) {
sec = string;
}
hr = parseInt(hr);
min = parseInt(min);
sec = parseInt(sec);
if(/^\d+$/.test(numTest)) {
var totalSec = hr*3600 + min*60 + sec;
if (totalSec > 0) {
timer(totalSec);
}
}
}
}
}
function focus() {
document.getElementById("box").focus();
}
function timeFormat(time) {
var sec = time % 60;
var totalMin = time / 60;
var min = Math.floor(totalMin % 60);
var string = "";
if (min == 0 && sec < 10) {
string = "0:0" + sec;
} else if (min == 0) {
string = "0:" + sec;
} else if (sec < 10) {
string = min + ":0" + sec;
} else {
string = min + ":" + sec;
}
return string;
}
Note that I am not using a button to trigger the form submission, I am simply using a onkeypress event to detect if the user hit the enter button (I wanted a cleaner design). Whenever the timer function is called, the text box flickers like it turns off for a second, than it comes back on in an instant. I have no idea what the problem is. I also have gotten no errors in console.
Am not sure what you are trying to achieve but from looking at your code, Hitting enter results in the page being reloaded, so I can't get to see the result.
I would however suggest you use jQuery to hide show your results, since you are already calling the script
$('#myform').hide();
$('#time').show();
The problem is this line of code. It turns the form off for a split second, which causes the blinking effect to occur. Simply remove this or comment it out.
document.getElementById("myform").style.display = "none";
If you want to hide the form, use jQuery's $('#myForm').hide() function. It's similar to <form id="myform" style="display:none;">
You could also try this:
<input type="text" id="timeInputBox" autocomplete="off" id="box" placeholder="00:00:00" onkeypress="checkBox(event)">
With this:
document.getElementById('timeInputBox').style.display = "none"; // JS
Or use this:
$('#timeInputBox').hide(); // jQuery
You may also want to move the jQuery <script> tag up higher in your <head> block. It needs to go before your call to your external <script src="javascript.js"></script> tag. Then you can use the $ and all of these functions from api.jquery.com in your .js file.

Javascript: Grab an array and sum all values

In my project, users can add timecode in and out points for their project, and the project automatically figures out the total duration of the timecode. But I want to add a function that will take all the available timecode durations, convert them to seconds, add them together, then convert the final number back to timecode and put it in a text input.
This is my code, but I keep getting syntax errors:
function timeToSeconds(t) {
var tc = t.split(':');
return parseInt(tc[0])*3600 + parseInt(tc[1])*60 + parseInt(tc[2]);
}
function tcDuration(tcin, tcout) {
function z(n){return (n<10?'0':'') + n;}
var duration = timeToSeconds(tcout) - timeToSeconds(tcin);
var hoursmins = Math.floor(duration / 60);
return z(Math.floor(hoursmins/60)) + ':' + z(hoursmins % 60) + ':' + z(duration % 60);
}
// Run this function every time a film_tc_out cell is changed
function film_tc_Duration() {
if (document.getElementById("film_tc_in").value == '') {var film_tc_in = '00:00:00';} else { var film_tc_in = document.getElementById("film_tc_in").value;}
if (document.getElementById("film_tc_out").value == '') {var film_tc_out = '00:00:00';} else { var film_tc_out = document.getElementById("film_tc_out").value;}
document.getElementById("film_tc_duration").value = tcDuration(film_tc_in, film_tc_out);
}
// Run this function every time a src_tc_out cell is changed
function src_tc_Duration() {
if (document.getElementById("src_tc_in").value == '') {var src_tc_in = '00:00:00';} else { var src_tc_in = document.getElementById("src_tc_in").value;}
if (document.getElementById("src_tc_out").value == '') {var src_tc_out = '00:00:00';} else { var src_tc_out = document.getElementById("src_tc_out").value;}
document.getElementById("src_tc_duration").value = tcDuration(src_tc_in, src_tc_out);
}
// Run this function every time a src_wd_out cell is changed
function src_wd_Duration() {
if (document.getElementById("src_wd_in").value == '') {var src_wd_in = '00:00:00';} else { var src_wd_in = document.getElementById("src_wd_in").value;}
if (document.getElementById("src_wd_out").value == '') {var src_wd_out = '00:00:00';} else { var src_wd_out = document.getElementById("src_wd_out").value;}
document.getElementById("src_wd_duration").value = tcDuration(src_wd_in, src_wd_out);
}
function total_tc_Duration() {
var val = document.getElementsByClassName('.asset_src_tc_duration');
var total_tc = 0;
var v;
for (var i = 0; i < val.length; i++) {
v = timeToSeconds(val[i]);
if (!isNaN(v)) total_tc += v;
}
return (total_tc);
}
function updateAssetTimecode() {
document.getElementById("timecode_total").value = total_tc_Duration();
}
Update: I've rewritten the For Loop to see if that helps - it currently gives me an answer now, although the answer is always "0". It's not spitting out any errors but it seems to think the variable val isn't a number?
Your tcDuration function won't work like you expect. You don't subtract the already calculated hours before doing the minutes calculation and the same with seconds.
function tcDuration(tcin, tcout) {
function z(n){return (n<10?'0':'') + n;}
var duration = timeToSeconds(tcout) - timeToSeconds(tcin);
var hoursmins = Math.floor(duration / 60);
return z(Math.floor(hoursmins / 60)) + ":" + z(hoursmins % 60) + ":" + z(duration % 60);
}

Taking var with JS prompt - how can I make it through HTML form?

I've been learning HTML/CSS/JavaScript for a couple of weeks now, and I am currently practicing on a mini project, which consists of letting people answer math questions, and validating their answers.
My current progress can be seen at http://dany.faceflow.com
I know I am probably not using the best strategy to develop this mini game, so any advice would be useful on that. However right now, the problem is that I am taking the user answer with a variable through JS prompt, and I want to do it via an HTML form (less annoying).
In my source code you can see this line within the function:
var userInput = prompt(numb1 + symbol + numb2);
Then, still in the same function, I have an if/else structure to compare the user's answer with the right answer. The code works, I just don't know how to make the prompt HTML-based instead. I've tried an html form with an ID and in the JS using getElementById, document.write and some other stuff but I never got it to work for that part.
(Here's all the JS)
var number1 = function() {
var numb1 = Math.floor(Math.random() * 41) + 10;
return numb1;
}
var number2 = function() {
var numb2 = Math.floor(Math.random() * 41) + 10;
return numb2;
}
var userAnswer = function() {
var numb1 = number1();
var numb2 = number2();
var randomSymbol = Math.random();
if (randomSymbol > 0.5) {
var symbol = "+";
} else {
var symbol = "-";
}
// add the math question in the html bubble
document.getElementById('bubble').innerHTML = numb1 + symbol + numb2;
// Prompts the user to give an answer. Change this to HTML.
var userInput = prompt(numb1 + symbol + numb2);
//var userInput = document.getElementById('tw').value;
if (symbol == "+" && userInput == (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "+" && userInput !== (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else if (symbol == "-" && userInput == (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "-" && userInput !== (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else {
alert("Something wrong happened. Try again.");
}
return userInput;
}
(The HTML)
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/stylesheet.css" />
<script src="js/script.js"></script>
<title>Improve Your Math Skills!</title>
</head>
<body>
<center>
<button onclick="userAnswer()">PLAY NOW!</button>
<div id="bubble"></div>
<div id="feedback"></div>
<!-- <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> -->
</center>
</body>
</html>
Thank you
You can use an input tag instead of the prompt. Change the HTML just as in Dinesh's answer;
<div id="bubble"></div>
<div id="inp" style="display: none;">
<input type="text" id="ans"></input> <button id="subBtn">Submit</button>
</div>
<div id="feedback"></div>
Now, for the JavaScript, there a few things to consider. Firstly, you have
var number1 = function() {
var numb1 = Math.floor(Math.random() * 41) + 10;
return numb1;
}
var number2 = function() {
var numb2 = Math.floor(Math.random() * 41) + 10;
return numb2;
}
Both functions do exactly the same thing; you don't need two separate functions to get two separate random numbers. So, only one function will suffice.
var number = function() {
return Math.floor(Math.random() * 41) + 10;
};
Secondly, now we have two functions. userAnswer to post a new question when 'Play Now!' is clicked and, say, evalAnswer to evaluate the answer written in the input field when 'Submit' is clicked.
In userAnswer, you generate two new random numbers and figure out which operation will be conducted on them. At this point, you can simply evaluate the answer yourself and store it in a global variable. This makes things easier when you evaluate the answer, you only need to do a simple comparison.
Other than that, you update innerHTML for bubble and display the div inp.
In evalAnswer, you get the value from ans and compare it with the previously computed value of the current answer, and then accordingly update feedback.innerHTML.
Here's the code;
//variable to maintain the current answer
var curAns = 0;
//Here, I get all the DOMElements I will use
var playBtn = document.getElementById('playBtn');
var bubble = document.getElementById('bubble');
var inp = document.getElementById('inp');
var ans = document.getElementById('ans');
var subBtn = document.getElementById('subBtn');
var feedback = document.getElementById('feedback');
//I add the event listeners
//This is equivalent to using 'onclick'
//in the HTML, and doing it this way is only
//my personal preference
playBtn.addEventListener('click', function() {userAnswer();}, false);
subBtn.addEventListener('click', function() {evalAnswer();}, false);
//Function to get random number
var number = function() {
return Math.floor(Math.random() * 41) + 10;
};
//This function will be executed when 'Play Now!' is clicked.
var userAnswer = function() {
//Get two separate random numbers in
//numb1 and numb2
var numb1 = number();
var numb2 = number();
var symbol = '';
var randomSymbol = Math.random();
//Determine the operation to be used
//and compute the corresponding correct answer for the current
//question
if (randomSymbol > 0.5) {
symbol = "+";
curAns = numb1+numb2;
} else {
symbol = "-";
curAns = numb1-numb2;
}
//Add math question to bubble
bubble.innerHTML = 'What is ' + numb1 + ' ' + symbol + ' ' + numb2 + '?';
feedback.innerHTML = '';
//Make inp div visible
inp.style.display = 'block';
//Reset input value to ''
ans.value = '';
};
//This function will be executed when 'Submit' is clicked
var evalAnswer = function() {
//Simply compare input value with computed
//answer and update feedback
if(parseInt(ans.value) !== curAns) {
feedback.innerHTML = 'Wrong answer, try again!';
}
else {
feedback.innerHTML = 'You got it right, congratulations!';
}
};
Here's a working example.
Hope that helped!
What I understand from your question is that you need the same functionality in HTML itself rather than driven by JS in a prompt box, if so,the below additions to your code should help:
HTML adition:
<div id="bubble"></div>
<div id="check_ans_div" style="display:none;">
<input type="text" id="txt_answer" />
<input type="submit" value="Check Answer" onclick="checkanswer()" />
</div>
<div id="feedback"></div>
JS changes:
var number1 = function() {
var numbx = Math.floor(Math.random() * 41) + 10;
return numbx;
}
var number2 = function() {
var numby = Math.floor(Math.random() * 41) + 10;
return numby;
}
var numb1=0; var numb2=0;
var userAnswer = function() {
numb1 = number1();
numb2 = number2();
var randomSymbol = Math.random();
if (randomSymbol > 0.5) {
var symbol = "+";
} else {
var symbol = "-";
}
// add the math question in the html bubble
document.getElementById('bubble').innerHTML = numb1 + symbol + numb2;
if(document.getElementById('check_ans_div').style.display=='none')
document.getElementById('check_ans_div').style.display='block';
document.getElementById('txt_answer').value='';
}
function checkanswer(){
var userInput= document.getElementById('txt_answer').value;
if (symbol == "+" && userInput == (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "+" && userInput !== (numb1 + numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else if (symbol == "-" && userInput == (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Congratulations!";
} else if (symbol == "-" && userInput !== (numb1 - numb2)) {
document.getElementById('feedback').innerHTML = "Wrong!";
} else {
alert("Something wrong happened. Try again.");
}
}

Categories