Wrap function into loop - javascript

I have script that updates time for one tag if I use querySelector and updateTime(inputTime.value); but how do I create loop so it works for all elements using querySelectorAll.
I've tried for, foreach, but I just can't understand what's my mistake. I'm using moment js, timezone detection.
JS
if (!sessionStorage.getItem('timezone')) {
var tz = jstz.determine() || 'UTC';
sessionStorage.setItem('timezone', tz.name());
}
var currTz = sessionStorage.getItem('timezone');
var inputTime = document.querySelectorAll(".input-time");
var output = document.querySelectorAll(".local");
function updateTime(theTime) {
var date = moment().format("YYYY-MM-DD");
var stamp = date + "T" + theTime + "Z";
var momentTime = moment(stamp);
var tzTime = momentTime.tz(currTz);
var formattedTime = tzTime.format('h:mm A');
output.textContent = "Time in " + currTz + ": " + formattedTime;
}
var i;
for (i = 0; i < inputTime.length; ++i) {
updateTime(inputTime[i].value);
}
HTML
<label for="input-time">Time in UTC: </label>
<input value="12:30" type="time" class="input-time">
<p class="local">x</p>
<label for="input-time">Time in UTC: </label>
<input value="12:30" type="time" class="input-time">
<p class="local">x</p>

Related

Unable to generate a multiplication table with user input in JavaScript

I have a page which prompts the user to enter a positive integer from 1 to 9, then the javascript code will generate a multiplication table from the input value all the way to 9. I am getting an error in which I cannot retrieve the value and do a multiplication with it.
function timesTable()
{
var values = document.getElementById('value1');
var showTables = '';
for (var i=1; i<9; i++) {
showTables += values + " x " + i +" = "+ values*i + "\n";
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
<label>Enter an integer from 1 to 9 : </label>
<input type="text" size=20 id=value1 name="value">
<button onclick="timesTable()">Generate times table</button><br> <br>
<p id="tables"></p>
Expected result:
You have to take the value of the element not the element itself
var values = document.getElementById('value1').value;
function timesTable()
{
var values = document.getElementById('value1').value;
var showTables = '';
for (var i=1; i<9; i++) {
showTables += values + " x " + i +" = "+ values*i + "<br>";
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
<label>Enter an integer from 1 to 9 : </label>
<input type="text" size=20 id=value1 name="value">
<button onclick="timesTable()">Generate times table</button><br> <br>
<p id="tables"></p>
You are trying to multiply the element itself. What you actually want is the value.
function timesTable()
{
var values = document.getElementById('value1').value;
var showTables = '';
for (var i=1; i<9; i++) {
showTables += values + " x " + i +" = "+ values*i + "\n";
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
<label>Enter an integer from 1 to 9 : </label>
<input type="text" size=20 id=value1 name="value">
<button onclick="timesTable()">Generate times table</button><br> <br>
<p id="tables"></p>
the javascript line in which you are trying to find value, is wrong as it will return the whole DOM and it's attributes and property.
You just have to find it's value, replace you line
var values = document.getElementById('value1');
with
var values = document.getElementById('value1').value;
This does what you want.
Note that if the user enters something unexpected, it may still fail. You can use an input of type="number" to require an integer (at least in some browsers.)
const userValue = document.getElementById("value1").value;
const p_tables = document.getElementById("tables");
let outputHtml = "";
for(let i = 1; i < 10; i++){
outputHtml += userValue + " x " + i + " = " + userValue * i + "<br/>";
}
p_tables.innerHTML = outputHtml;
you are using input field as text for table generation its better to use Number as input type and to get the value of input field you have to use value function as used in above code and for line break use
<\br>(please ignore '\').
function timesTable()
{
var values = document.getElementById('value1').value;
var showTables = '';
for (var i=1; i<=9; i++) {
showTables += values + " x " + i +" = "+ values*i + "<br>";
}
document.getElementById('tables').innerHTML = showTables;
}
<label>Enter an integer from 1 to 9 : </label>
<input type="Number" size=20 id=value1 name="value">
<button onclick="timesTable()">Generate times table</button><br> <br>
<p id="tables"></p>

How can I get future date month and year by inputting opening date and duration month using JavaScript

when I select date and input month duration then other field will display the target date
how can I implement this,Please anybody help me to do that.my form is that
// I have tried to do that
$("#duration").keyup(function(){
var duration = $(this).val();
var open_date = $("#openDate").val();
// i want to use same function and method
// here will next code
var targetDate = new Date(open_date);
targetDate.setMonth(targetDate.getMonth() + duration);
var dd = targetDate.getDate();
var mm = targetDate.getMonth() + 1;
var yyyy = targetDate.getFullYear();
var dateString = dd + "/" + mm + "/" + yyyy;
$('#targetDate').val(dateString);
// i have do that but do not get my espect out put
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Open Date :
<input type="date" id="openDate"><br><br>
Duration Month:
<input type="text" id="duration" placeholder="mm"><br><br>
Target Date :
<input type="text" id="targetDate" placeholder="dd-mm-yyyy">
Please try this:
$("#duration").keyup(function(){
var duration = $(this).val();
var open_date = $("#openDate").val();
// i want to use same function and method
// here will next code
var targetDate = new Date(open_date);
targetDate.setMonth(targetDate.getMonth() + parseInt(duration));
var dd = targetDate.getDate();
var mm = targetDate.getMonth() + 1;
var yyyy = targetDate.getFullYear();
var dateString = dd + "/" + mm + "/" + yyyy;
$('#targetDate').val(dateString);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Open Date :
<input type="date" id="openDate"><br><br>
Duration Month:
<input type="text" id="duration" placeholder="mm"><br><br>
Target Date :
<input type="text" id="targetDate" placeholder="dd-mm-yyyy">

AWS Javascript SDK EC2 DescribeInstances

I am trying to get date & no. of instances spin-up on that day.
Here is my code , i am beginner in development & in javascript.
so forgive me in advance for any immature code.
after getting startdate & end date , dates are stored in listDate array.
hours of a day is stored in hourArray.
then using JS SDK for AWS to get no. of instances spinned up on specific date.
ec2.describeInstances is not working as expected here ,
sometimes , i got output from ec2.describeInstances correctly , but it is always picking end date in all while loop iterations.
most of the time , ec2.describeInstances doesnt even execute.
function applyFilters() {
var listDate = [];
demo1.innerHTML = '';
var startDate = document.getElementById("fromdate").value;
var endDate = document.getElementById("todate").value;
//alert(startDate);
//alert(endDate);
var dateMove = new Date(startDate);
var strDate = startDate;
while (strDate < endDate){
var strDate = dateMove.toISOString().slice(0,10);
listDate.push(strDate);
dateMove.setDate(dateMove.getDate()+1);
};
//alert(listDate);
//document.getElementById('demo1').innerHTML = "Your selected dates are";
//demo2.innerHTML += "<br>";
//document.getElementById('demo3').innerHTML = listDate;
alert(listDate);
var i = 0;
var j = listDate.length;
alert(j);
while (i < j){
alert(i);
alert(listDate[i]);
var hourArray = [];
var d = listDate[i];
for (var h = 0; h <= 9; h++) {
hourArray.push(d + 'T' + '0' + h + '*');
}
for (var m = 10; m <= 23; m++) {
hourArray.push(d + 'T' + m + '*');
}
alert(hourArray);
var ec2 = new AWS.EC2();
AWS.config.update({
region: "xxxxxxx",
accessKeyId: "xxxxxxxxxxxxxxxxxxxxx",
secretAccessKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
});
i++;
var params = {
Filters: [
{
Name: 'launch-time',
Values: hourArray
}]
};
//alert("Specified launch-times are: " + hourArray);
ec2.describeInstances(params, function(err, data, d) {
//alert(data);
if (err) {
//demo5.innerHTML = 'ERROR:' + err;
console.log(err);
} else {
var no_of_inst = data.Reservations.length;
//demo4.innerHTML += "<br>";
//document.getElementById('demo5').innerHTML = 'Instances migrated on' + listdate[i] + 'are: ' + no_of_inst;
alert("Instances migrated on" + d + "are: " + no_of_inst);
}
});
}
}
<!DOCTYPE html>
<html>
<head>
<title>Migration Status</title>
<!--<link rel="stylesheet" href="styles.css">-->
<div>
<h3> M I G R A T I O N - S T A T U S </h3>
</div>
<meta charset="utf-8">
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.208.0.min.js"></script>
</head>
<body>
<p>Select Filters to get your ec2 graph :</p>
<form>
<div class = "css-grid1">
<label> Launch-time: </label>
</div>
<div class = "css-inlineblock1">
<label for="fromdate">From Date:</label>
<input type="date" id="fromdate" name="fromdate" min="2017-01-01">
<label for="todate">To Date:</label>
<input type="date" id="todate" name="todate">
</div>
<div class = "css-button">
<input type="submit" id="sbmt" onclick="applyFilters()">
</div>
<div id="demo1"></div>
<div id="demo2"></div>
<div id="demo3"></div>
<div id="demo4"></div>
<div id="demo5"></div>
<div id="demo6"></div>
<div id="demo7"></div>
<div id="demo8"></div>
</form>
<script>
</script>
</body>
</html>

Uncaught rangeError : Invalid string length

so i have just started to learn javascript, literally had 2 classes on it. So my knowledge is very very limited. But I am trying to make an appointment application and i keep receiving a Uncaught rangeError :Invalid string length error, and i have no idea why or how to fix it. Basically I have been given some code to copy without much explanation to it, so if anyone can help me with this error it would be greatly appreciated. The code where the error is appearing is below and i believe it is the line table += appt.tableRow(); which is causing the issue. There is obviously more to this code, but not sure if it needs to be given, as the issue is in the showTable function
Edit : I just added the whole javascript code to make it easier
var Appointment = function(subject, description,date, time) {
this.subject = subject;
this.description = description;
this.datetime = new Date(date + " " + time);
this.completed = false;
};
Appointment.prototype.isDue = function(){
var now = new Date();
if(this.datetime > now){
return false;
} else {
return true;
}
};
Appointment.prototype.whenDue = function(){
return this.datetime - new Date();
}
Appointment.prototype.toString = function(){
var s = this.subject +'\n'+
this.datetime.toString() + '\n';
if(this.completed){
s +="Not Completed\n\n";
}
return s
};
Appointment.prototype.howManyDaysTill = function() {
var ms = (this.datetime - new Date()) / 24/60/60/1000
return ms;
};
Appointment.prototype.howManyHoursTill = function () {
var hours = (this.datetime - new Date()) /60/60/1000
return hours;
};
Appointment.prototype.getDate = function() {
return this.datetime.toDateString();
};
Appointment.prototype.getTime = function (){
return (this.datetime.getHours()) + ":" + (this.datetime.getMinutes());
};
Appointment.prototype.tableRow = function(){
var tr = "<tr><td>" + this.getDate() + "</td><td>" +
this.getTime() + "</td><td>" + this.subject +
"</td></tr>";
return tr;
};
var appointments = [];
window.onload = function(){
var newButton = document.getElementById("new");
newButton.onclick = function () {
var subj = prompt("Enter a subject title for the appointment");
var desc = prompt("Enter a description for the appointment");
var date = prompt("Enter the appointment date in the format (e.g) 'Sep
25, 2012");
var time = prompt("Enter the appointment time in the format hh:mm");
var a = new Appointment((subj,desc,date,time));
appointments.push(a);
return showTable();
};
var showTable = function() {
var tableDiv = document.getElementById("table"),
table = "<table border='1'>" +
"<thead><th>Date</th><th>Time</th><th>Subject</th><th>Completed</th>
</thead>";
for (var i = 0, j = appointments.length; i < j; j++) {
var appt = appointments[i];
table += appt.tableRow();
}
table += "</table>";
tableDiv.innerHTML = table;
};
}
HTML5
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="appointments.js"></script>
<title>Appointments</title>
</head>
<body>
<button id="new">New Appointment</button>
<div id ="table"></div>
<header>
<h1>
Appointments Book
</h1>
<p> Enter appointment details and press OK to add, Cancel to revert.</p>
</header>
<table>
<tr>
<td>Subject : </td> <td>input type="text" size="40" id="subject"</td>
</tr>
<tr>
<td>Description</td>
<td>
<textarea rows = "5" cols=""50" maxlength="200" id="description">
</textarea>
</td>
</tr>
<tr> <td>Due Date:</td><td><input type ="date" id="duedate"/></td>
</tr>
</table>
<button id = "OK">OK </button><button id = "cancel">Cancel</button>
<hr/>
</body>
</html>
The for loop must increment on i and not on j. The current one is causing a infinite looping and hence the following line is creating a string that is too big to handle by the JS engine and hence the error
table += appt.tableRow();

How to insert the value of javascript into html [duplicate]

This question already has answers here:
How to Add Two Days from Current Date to the Value of a Hidden Input
(3 answers)
How to insert Javascript variables into a database
(1 answer)
Closed 5 years ago.
I want to get the javascript value into my html input value and insert it into the database after the user click the submit
<script>
var currentDate = new Date();
if (currentDate.getDay() == 5) {
var numberOfDaysToAdd = 4; //Adding 4 to skip sat. & sun. if Friday
} else {
var numberOfDaysToAdd = 2; //Adding 2 days if not Friday
}
currentDate.setDate(currentDate.getDate() + numberOfDaysToAdd);
var dd = currentDate.getDate();
var mm = currentDate.getMonth() + 1;
var y = currentDate.getFullYear();
var someFormattedDate = y + '-' + mm + '-' + dd;
document.getElementById("display").innerHTML = someFormattedDate;
</script>
<?php
echo $_GET['someFormattedDate'];
?>
<input type="text" class="w8em format-y-m-d highlight-days-67 range-low-today" name="due_date" id="sd" maxlength="10" value="<?php echo " someFormattedDate " style="border: 3px double #CCCCCC; " disabled/>
Since your input id is sd,
document.getElementById("sd").value = someFormattedDate;
Note: Elements with Disabled attribute are not submitted, enable it before submit.
Full Code:
<?php
echo $_GET['due_date'];
?>
<form name="myform" id="myform" method="GET">
<input type="text" class="w8em format-y-m-d highlight-days-67 range-low-today" name="due_date" id="sd" maxlength="10" style="border: 3px double #CCCCCC; " readonly/>
<input type="submit" name="btn_submit" value="Submit">
</form>
<script>
var currentDate = new Date();
if (currentDate.getDay() == 5) {
var numberOfDaysToAdd = 4; //Adding 4 to skip sat. & sun. if Friday
} else {
var numberOfDaysToAdd = 2; //Adding 2 days if not Friday
}
currentDate.setDate(currentDate.getDate() + numberOfDaysToAdd);
var dd = currentDate.getDate();
var mm = currentDate.getMonth() + 1;
var y = currentDate.getFullYear();
var someFormattedDate = y + '-' + mm + '-' + dd;
document.getElementById("sd").value = someFormattedDate;
</script>
First, put the JavaScript code after the input you want to use. That way the input exists on the page when the code executes.
Second, use the actual id of the input.
Third, set the .value property.
Fourth, put the input in a form.
Fifth, don't disable the input.
Something like this:
<form>
<input type="text" class="w8em format-y-m-d highlight-days-67 range-low-today" name="due_date" id="sd" maxlength="10" style="border: 3px double #CCCCCC;" disabled/>
<input type="submit" value="Submit" />
</form>
<script>
// The rest of your JavaScript code, formatting your date value
document.getElementById("sd").value= someFormattedDate;
</script>
Unless otherwise specified, this <form> will submit a GET request to the current URL by default when the submit button is clicked.
Aside from that it's not really clear to me what you're trying to do with the PHP code here. Why you're trying to output a value that hasn't been submitted yet, or output a literal string, or whatever you're attempting.
<script>
var currentDate = new Date();
if (currentDate.getDay() == 5) {
var numberOfDaysToAdd = 4; //Adding 4 to skip sat. & sun. if Friday
} else {
var numberOfDaysToAdd = 2; //Adding 2 days if not Friday
}
currentDate.setDate(currentDate.getDate() + numberOfDaysToAdd);
var dd = currentDate.getDate();
var mm = currentDate.getMonth() + 1;
var y = currentDate.getFullYear();
var someFormattedDate = y + '-' + mm + '-' + dd;
document.getElementById("sd").innerHTML = someFormattedDate;
</script>
Description:- You are binding data with wrong element.

Categories

Resources