I have a reset function in my codes that is keeping my form on a reloading loop.
When I click on my Calculate Button, the divtext that I am trying to display just "Blink" and it will go off.
I only want it to reset when reset button is clicked though. Don't know where it went wrong. Here are my codes.
function calculateDate() {
var startDate = document.getElementById("startDate").value;
var endDate = document.getElementById("endDate").value;
var dvtextless60 = document.getElementById("dvtextless60");
var dvtext61182 = document.getElementById("dvtext61182");
var dvtextmore183 = document.getElementById("dvtextmore183");
var Difference_In_Time = new Date(endDate).getTime() - new Date(startDate).getTime();
var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
if (Difference_In_Days < 60){
document.getElementById("dvtextless60").style.display = "block";
} else if (Difference_In_Days > 60 && Difference_In_Days <= 182){
document.getElementById("dvtext61182").style.display = "block";
} else {
document.getElementById("dvtextmore183").style.display = "block";
}
document.getElementById("daysCalculator").innerHTML = greeting;
}
function resetForm(){
document.getElementById('rCalculator').reset();
}
<form id="rCalculator">
<pre>
Enter Start Date: <input type="date" name="startDate" id="startDate"/><br>
Enter End Date: <input type="date" name="endDate" id="endDate"/><br>
Total Days : <span id="daysCalculator"></span>
<div id="dvtextless60" style="display:none">
<span style="font-size:18px"><b>Too Short</b></span>
<br>
</div>
<div id="dvtext61182" style="display:none">
<span style="font-size:18px"><b>Almost There</b></span>
</div>
<div id="dvtextmore183" style="display:none">
<span style="font-size:18px"><b>Too Long</b></span>
</div>
<button id="calculate" onclick="calculateDate();">Calculate</button> <button id="reset" onclick="resetForm();">Reset</button>
</pre>
You can solve this adding a type="button" to your reset button.
Considering the fact that you are using html form
I suggest you to edit your button with <type="submit"> and <type="reset">
and you can remove the button onClick and use form onsubmit={}
<form id="rCalculator" onsubmit="calculateDate()">
Enter Start Date: <input type="date" name="startDate" id="startDate"/><br>
Enter End Date: <input type="date" name="endDate" id="endDate"/><br>
<button id="calculate" type="submit">Calculate</button>
<button id="reset" type="reset">Reset</button>
</form>
Have an event.preventDefault() method in your calculate function. This way you can eliminate resetForm() function.
Related
I am asking users to select a Start Date and End Date from the calendar.
I want to display the dates they have picked in a summary page.
For Example:
Your Start Date : [Date User has picked from Calendar in DD MM YYY]
Your End Date : [Date User has picked from Calendar in DD MM YYY]
Is there any way for me to do this?
function calculateDate() {
var startDate = document.getElementById("startDate").value;
var endDate = document.getElementById("endDate").value;
var dvtextless60 = document.getElementById("dvtextless60");
var dvtext61182 = document.getElementById("dvtext61182");
var dvtextmore183 = document.getElementById("dvtextmore183");
var Difference_In_Time = new Date(endDate).getTime() - new Date(startDate).getTime();
var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
if (Difference_In_Days < 60){
document.getElementById("dvtextless60").style.display = "block";
} else if (Difference_In_Days > 60 && Difference_In_Days <= 182){
document.getElementById("dvtext61182").style.display = "block";
} else {
document.getElementById("dvtextmore183").style.display = "block";
}
document.getElementById("numofdays").innerHTML = Difference_In_Days;
document.getElementById("displaysummary").innerHTML = startDate;
}
function resetForm(){
document.getElementById('rCalculator').reset();
location.reload();
}
<body>
<form id="rCalculator">
<pre>
Enter Start Date: <input type="date" name="startDate" id="startDate"/><br>
Enter End Date: <input type="date" name="endDate" id="endDate"/><br>
Total Days : <span id="numofdays"></span>
<span id="displaysummary"></span>
<div id="dvtextless60" style="display:none">
<span style="font-size:18px"><b>Too Short</b></span>
<br>
</div>
<div id="dvtext61182" style="display:none">
<span style="font-size:18px"><b>Almost There</b></span>
</div>
<div id="dvtextmore183" style="display:none">
<span style="font-size:18px"><b>Too Long</b></span>
</div>
<button type="button" id="calculate" onclick="calculateDate();">Calculate</button> <button type="button" id="startover" onclick="resetForm();">Reset</button>
</pre>
</form>
</body>
function calculateDate() {
var startDate = document.getElementById("startDate").value;
var endDate = document.getElementById("endDate").value;
var dvtextless60 = document.getElementById("dvtextless60");
var dvtext61182 = document.getElementById("dvtext61182");
var dvtextmore183 = document.getElementById("dvtextmore183");
var Difference_In_Time = new Date(endDate).getTime() - new Date(startDate).getTime();
var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
if (Difference_In_Days < 60){
document.getElementById("dvtextless60").style.display = "block";
} else if (Difference_In_Days > 60 && Difference_In_Days <= 182){
document.getElementById("dvtext61182").style.display = "block";
} else {
document.getElementById("dvtextmore183").style.display = "block";
}
document.getElementById("numofdays").innerHTML = Difference_In_Days;
document.getElementById("displaysummary").innerHTML ="Your Start Date :" + getFormattedDate(startDate) + "<br>Your End Date :" + getFormattedDate(endDate);
}
function resetForm(){
document.getElementById('rCalculator').reset();
location.reload();
}
function getFormattedDate(d){
return d.substr(8,2) + " " + d.substr(5,2) + " " + d.substr(0,4)
}
<body>
<form id="rCalculator">
<pre>
Enter Start Date: <input type="date" name="startDate" id="startDate"/><br>
Enter End Date: <input type="date" name="endDate" id="endDate"/><br>
Total Days : <span id="numofdays"></span>
<span id="displaysummary"></span>
<div id="dvtextless60" style="display:none">
<span style="font-size:18px"><b>Too Short</b></span>
<br>
</div>
<div id="dvtext61182" style="display:none">
<span style="font-size:18px"><b>Almost There</b></span>
</div>
<div id="dvtextmore183" style="display:none">
<span style="font-size:18px"><b>Too Long</b></span>
</div>
<button type="button" id="calculate" onclick="calculateDate();">Calculate</button> <button type="button" id="startover" onclick="resetForm();">Reset</button>
</pre>
</form>
</body>
I'm stuck on a problem. I'm working on an exercise that generates a random integer between 1-10. The user will submit a number from 1-10 in the input box. If a match occurs, the user will get an alert notifying them of success.
I'm stuck on getting the number from the user input. I want to log to the console the form input, but for the life of me, I cannot figure this out. I've tried changing the form type="number", type="text" and tried using parseInt().
Anything glaring in my code?
function exerciseEight() {
let input = document.querySelector("#number").value;
let button = document.querySelector("#guess");
let valueInt = parseInt(input, 10);
let number = Math.ceil(Math.random() * 10);
console.log(number);
button.onclick = function() {
console.log(input);
};
}
exerciseEight();
<body>
<div class="container container-fluid">
<p><strong>Exercise Eight:</strong> Guess a Number between 1 and 10.</p>
<form>
<div class="form-group">
<label for="number">Choose Number:</label>
<input id="number" value="" type="text" name="number" />
</form>
<!-- Result will go here -->
<p id="result"></p>
</div>
<button class="btn btn-dark" id="guess" type="submit">SUBMIT</button>
</body>
You need to get the input value when the user clicks. You're setting input and all the other variables that depend on it when the page is first loaded.
function exerciseEight() {
let button = document.querySelector("#guess");
let number = Math.ceil(Math.random() * 10);
button.onclick = function() {
let input = document.querySelector("#number").value;
let valueInt = parseInt(input, 10);
console.log(number, input);
};
}
exerciseEight();
<body>
<div class="container container-fluid">
<p><strong>Exercise Eight:</strong> Guess a Number between 1 and 10.</p>
<form>
<div class="form-group">
<label for="number">Choose Number:</label>
<input id="number" value="" type="text" name="number" />
</form>
<!-- Result will go here -->
<p id="result"></p>
</div>
<button class="btn btn-dark" id="guess" type="submit">SUBMIT</button>
</body>
The problem is that you are calling the function when the page loads, so it gets the values from the start, and doesn't change them at runtime when user enters input. You should call the function when user clicks the button.
function exerciseEight() {
let input = document.querySelector("#number").value;
let valueInt = parseInt(input, 10);
let number = Math.ceil(Math.random() * 10);
console.log(number);
}
let button = document.querySelector("#guess");
button.onclick = exerciseEight;
<body>
<div class="container container-fluid">
<p><strong>Exercise Eight:</strong> Guess a Number between 1 and 10.</p>
<form>
<div class="form-group">
<label for="number">Choose Number:</label>
<input id="number" value="" type="text" name="number" />
</form>
<!-- Result will go here -->
<p id="result"></p>
</div>
<button class="btn btn-dark" id="guess" type="submit">SUBMIT</button>
</body>
<!-- This inputs values coming from the date pickers. -->
<input type="text" name="checkin" value="2019-09-11"/>
<input type="text" name="checkout" value="2019-09-13"/>
<input type="text" name="nightprice"/> <!-- When an user write a price -->
<input type="text" name="totalprice"/> <!-- This will be calculated -->
Calculate will be like this ;
The days between checkin and checkout will be calculated and it will be multiplied by days and price.
For example 2019-09-11 between 2019-09-13 is 2 day and if user write 200 on nightprice it will calculate this like 2x200 = 400 and will be placed at totalprice input
my question is how can i do this with jquery without refresh page.
Here's a simple jQuery way to do it. The poor-mans approach would be to just listen to any input change event and re-rerun your calculation. However, if you've got more inputs on your page / form than mentioned in this question (which you likely do) then I would use more specific selectors than simple listening to all inputs. Maybe look into a class? A form onsubmit function? There's plenty of ways to handle that.
const calculatePrice = (checkin, checkout, pricePerNight) => {
checkin = new Date(checkin);
checkout = new Date(checkout);
const dayDiff = Math.round( (checkout - checkin) / (1000 * 60 * 60 * 24 ) );
return dayDiff * pricePerNight;
};
$(document).ready( e => {
const nightPriceInput = $('input[name="nightprice"]');
const checkinInput = $('input[name="checkin"]');
const checkoutInput = $('input[name="checkout"]');
const totalPrice = $('input[name="totalprice"]');
$('input').on('change', () => {
const price = calculatePrice(checkinInput.val(), checkoutInput.val(), nightPriceInput.val());
totalPrice.val(price);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- This inputs values coming from the date pickers. -->
<input type="text" name="checkin" value="2019-09-11"/>
<input type="text" name="checkout" value="2019-09-13"/>
<input type="text" name="nightprice"/> <!-- When an user write a price -->
<input type="text" name="totalprice"/> <!-- This will be calculated -->
var startArray = $("#start").val().split("-");
var finishArray = $("#finish").val().split("-");
var yearDiff = finishArray[0] - startArray[0];
var monthDiff = finishArray[1] - startArray[1];
var dayDiff = finishArray[2] - startArray[2];
$("#price").on('change', function(){
var price = $("#price").val();
var total = ((yearDiff*365) + (monthDiff*30) + (dayDiff)) * price;
$("#total").html("$" + total);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="start" type="text" name="checkin" value="2019-09-11"/>
<input id="finish" type="text" name="checkout" value="2019-09-13"/>
<input id="price" type="text" name="nightprice" value="300"/>
<div id="total">
</div>
See
<input type="text" name="checkin" value="2019-09-11" id="checkin" />
<input type="text" name="checkout" value="2019-09-13" id="checkout" />
<input type="text" name="nightprice" onkeyup="calculate(this)"/> <!-- When an user write a price -->
<input type="text" name="totalprice" id="totalprice" />
<script>
var calculate = function(element) {
// get value
var price = element.value;
var checkin = document.getElementById("checkin");
checkin = checkin.getAttribute('value').replace(/[\-]+/g,'');
var checkout = document.getElementById("checkout");
checkout = checkout.getAttribute('value').replace(/[\-]+/g,'');
var totalprice = document.getElementById('totalprice');
// difference
var difference = checkout - checkin;
// calcule final price
var finalprice = price * difference;
// set final price
totalprice.setAttribute('value', finalprice);
}
</script>
I'm making a page to easily calculate when I could go home from work. The page should set a start date when loaded. That way I don't have to know when I started working and just open my browser. Then by clicking one of the buttons it should just add some hours.
The example is one of the many things I've tried already. But this one is close I think. Any suggestions are welcome. I didn't include jquery because of the small scale this has.
function reset() {
var date = new Date();
var hour = date.getHours(),
min = date.getMinutes();
hour = (hour < 10 ? "0" : "") + hour;
min = (min < 10 ? "0" : "") + min;
var timestamp = hour + ":" + min;
document.getElementById("start_time").value = timestamp;
}
function add_time_76() {
var start = document.getElementById("start_time").value;
document.getElementById("end_time").value = start + 7, 6;
}
function getTotal() {
var start = document.getElementById("start_time").value;
var end = document.getElementById("end_time").value;
document.getElementById("total").value = end - start;
}
<body onload="reset()">
<p>Start time: <input name="start_time" type="time" /></p>
<p>Time to go home: <input name="end_time" type="time" /></p>
<p>Total hours: <input type="text" name="total" readonly></p>
<button onclick="add_time_76()">Add 7,6h</button>
<button onclick="add_time_8()">Add 8h</button>
<br><br>
<button onclick="getTotal()">Calculate Total</button>
<br><br>
<button onclick="reset()">Reset</button>
</body>
The time fields aren't getting populated when I want them to be.
Just add a id to your inputs.
<p>Start time: <input id="start_time" name="start_time" type="time" /></p>
<p>Time to go home: <input id="end_time" name="end_time" type="time" /></p>
<p>Total hours: <input id="total" type="text" name="total" readonly></p>
I'm new to javascript. The following code is my practice for designing a timer. It works for the start button when clicked, but not for the pause button. I've spent hours trying to figure it out, but I still have no clue. Any help would be highly appreciated!
<!DOCTYPE html>
<html>
<body>
<div class="inputs" id="inputs-div">
<input id="hours" type="number" name="hours" max="100" min="0" value="1"/>
<input id="minutes" type="number" name="minutes" max="59" min="0" value="10"/>
</div>
<div class="countdown-div">
<input id="countdownTimer" type="text" style="display: none" />
</div>
<div class="buttons">
<button id="button-start">Start</button>
<button id="button-pause">Pause</button>
<button id="button-cancel" style="display: none">Cancel</button>
<button id="button-resume" style="display: none">Resume</button>
</div>
<script>
var hours = document.getElementById("hours").value,
mins = document.getElementById("minutes").value,
maxtime = parseInt(hours) * 3600 + parseInt(mins) * 60;
document.getElementById("button-start").addEventListener("click", myFunction);
function myFunction() {
document.getElementById("button-start").style.display = "none";
document.getElementById("button-cancel").style.display = "block";
document.getElementById("inputs-div").style.display = "none";
document.getElementById("countdownTimer").style.display = "block";
}
function timedCount() {
document.getElementById('countdownTimer').value=Math.floor(maxtime/3600)+":"
+Math.floor(maxtime%3600/60)+":"+maxtime % 3600 % 60;
maxtime--;
setTimeout("timedCount()",1000);
}
var t=setTimeout("timedCount()",1000);
function timerPause() {
clearTimeout(t);
}
document.getElementById("button-pause").addEventListener("click", timerPause);
</script>
</body>
</html>
You have the line setTimeout("timedCount()",1000); inside your timedCount() function.
You need to assign it to t so you can still clear it. Also, I don't know why your function names are in strings when you do setTimeout, I'm not sure if that works. Usually you just put the function name without ()
function timedCount() {
document.getElementById('countdownTimer').value=Math.floor(maxtime/3600)+":"
+Math.floor(maxtime%3600/60)+":"+maxtime % 3600 % 60;
maxtime--;
t = setTimeout(timedCount,1000); <--- this line
}
You should really look into setInterval and clearInterval.