My code should work but i guess i made i mistake somewhere, i'm trying to change the sound of an alarm, it's actually working but :
If i'm trying to change the sound of the alarm x and an alarm x+1 has already been add, the sound of x won't change anymore.
It means my code only change the value of the last alarm but i don't know why.
Here is my HTML and my JS, i hope you'll have an answer.`
(function(){
setInterval(function(){
var temps = new Date();
var h = temps.getHours();
var m = temps.getMinutes();
var s = temps.getSeconds();
if(h < 10) {
h = "0" + h;
}
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
document.getElementById("heure").textContent = h + ":" + m + ":" + s;
},1000);
var i = 1;
document.getElementById("plus").addEventListener('click', function() {
//Ajout
var cp = document.getElementById("ligne").cloneNode(true);
var div = document.createElement("div");
div.setAttribute("id", "num" + i);
var liste = document.getElementById("liste");
liste.appendChild(div);
liste.appendChild(cp);
document.querySelector("#liste #num" + i + " + #ligne").hidden = false;
//Suppression
var l_sup = document.querySelector("#liste #num" + i + " + #ligne");
var l2_sup = document.querySelector("#num" + i);
document.querySelector("#num" + i + " + #ligne #del").addEventListener('click', function() {
l_sup.parentNode.removeChild(l_sup);
l2_sup.parentNode.removeChild(l2_sup);
});
audio = document.querySelector("#num" + i + " + #ligne #audio");
select = document.querySelector("#num" + i + " + #ligne #son");
document.querySelector("#num" + i + " + #ligne #son").addEventListener("click", function(){
value = select.value;
audio.setAttribute("src", value);
});
i++;
});
})();
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<head>
</head>
<body>
<p>Il est : <span id = "heure"></span></p>
<div id = "liste">
<div hidden id="ligne">
<input checked type="checkbox" id="cb"/>
<input type="number" placeholder="Heures" name="h" id="h"/>
<input type="number" placeholder="Minutes" name="m" id="m"/>
<input type="text" name="desc" placeholder="Nom de l'alarme" id="desc"/>
<select id="son"/>
<option value="Trance.mp3" id="son1">Trance</option>
<option value="Classic.mp3" id="son2">Classic</option>
<option value="Dubstep.mp3" id="son3">Dubstep</option>
</select>
<audio controls loop id="audio" src = "Trance.mp3"></audio>
<button id="del">Supprimer</button>
</div>
</div>
<div>
<button id="plus">Ajouter</button>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
`
The major problem is in this piece of code inside click listener of <select>.
value = select.value;
audio.setAttribute("src", value);
As select and audio variable will always have the value of last added element. So it will always make changes to last <audio> element. So we need to get the select and audio from the this object inside the <select> click listener. this.nextElementSibling will give us the <audio> placed next to <select> on which the click event is fired :
value = this.value; // for getting value of current select element
this.nextElementSibling.setAttribute("src", value); // for getting audio element next to current select element
Sample Working Code:
(function(){
setInterval(function(){
var temps = new Date();
var h = temps.getHours();
var m = temps.getMinutes();
var s = temps.getSeconds();
if(h < 10) {
h = "0" + h;
}
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
document.getElementById("heure").textContent = h + ":" + m + ":" + s;
},1000);
var i = 1;
document.getElementById("plus").addEventListener('click', function() {
//Ajout
var cp = document.getElementById("num0").cloneNode(true);
cp.setAttribute("id", "num" + i);
var liste = document.getElementById("liste");
liste.appendChild(cp);
document.querySelector("#liste #num" + i).hidden = false;
//Suppression
var l_sup = document.querySelector("#liste #num" + i);
var l2_sup = document.querySelector("#num" + i);
document.querySelector("#num" + i + " button").addEventListener('click', function() {
l_sup.parentNode.removeChild(l_sup);
l2_sup.parentNode.removeChild(l2_sup);
});
audio = document.querySelector("#num" + i + " audio");
select = document.querySelector("#num" + i + " select");
document.querySelector("#num" + i + " select").addEventListener("click", function(){
value = this.value;
this.nextElementSibling.setAttribute("src", value);
});
i++;
});
})();
<!DOCTYPE html>
<html>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<head>
</head>
<body>
<p>Il est : <span id = "heure"></span></p>
<div id = "liste">
<div hidden id="num0">
<input checked type="checkbox" id="cb"/>
<input type="number" placeholder="Heures" name="h" id="h"/>
<input type="number" placeholder="Minutes" name="m" id="m"/>
<input type="text" name="desc" placeholder="Nom de l'alarme" id="desc"/>
<select/>
<option value="Trance.mp3">Trance</option>
<option value="Classic.mp3">Classic</option>
<option value="Dubstep.mp3">Dubstep</option>
</select>
<audio controls loop src = "Trance.mp3"></audio>
<button>Supprimer</button>
</div>
</div>
<div>
<button id="plus">Ajouter</button>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
P.S.: As Brahma Dev commented, id should always be unique
Instead of using click event to update audio src. Use change event. Then audio should change fluently.
document.querySelector("#num" + i + " + #ligne #son").addEventListener("change", function(){
value = select.value;
audio.setAttribute("src", value);
});
Here is a working JSbin https://jsbin.com/ficodot/edit?html,js,output
Related
This simple code is supposed to give an alert when the button is pressed the amount of times you wrote in the input. There is no error or something but the code just doesn't work. Am I stupid and did I miss something or is the logic of my code just wrong? and how do make it work?
var rand1, rand2, text1, text2
let count = 0;
var correct = 0;
function button(){
text1 = document.getElementById("number").value;
rand1 = Math.floor(Math.random() * text1);
rand2 = Math.floor(Math.random() * text1);
var html = "<br><br><input type='number' id='id'> <button onclick=' check() '> check </button> " + Number(rand2) + '+' + Number(rand1);
document.getElementById('div').innerHTML = html;
}
function check(){
text2 = document.getElementById('questions').value;
var answer = rand1 + rand2;
var text11 = document.getElementById('id').value;
if(answer == text11) {
var h = "<input type='number' id='id'> " + " <button onclick=' check() '> check </button> " + correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = h;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
correct = correct + 1;
count = count + 1;
} else {
count = count + 1;
var b = "<input type='number' id='id'> " + " <button onclick=' check() '> check </button> " + correct + '/' + text2 + '<br>' + count;
document.getElementById('div').innerHTML = b;
setTimeout(wait, 3000);
document.getElementById("but").disabled = true;
}
if (count === text2){
alert(correct + '/' + text2);
}
function wait(){
button()
}
}
<p>maximum number:<input type="text" id="number"></p>
<p>how many questions?<input type="text" id="questions"></p>
<button onclick="button()" id = 'but'> ok </button>
<div id = 'div'> </div>
The .value returns a string and you must convert it into a number (if you want to) before using it.
So in line 6 do this:
text1 = Number(document.getElementById("number").value);
and also in the check() function:
text2 = Number(document.getElementById('questions').value);
Hope that works.
So the code/script is below. I want it to update without having to refresh the page. I tried putting it in a loop but the page just never loaded. Can anyone help?
Thanks
var dt = new Date();
document.getElementById("datetime").innerHTML = (("0" + dt.getDate()).slice(-2)) + "." + (("0" + (dt.getMonth() + 1)).slice(-2)) + "." + (dt.getFullYear()) + " " + (("0" + dt.getHours()).slice(-2)) + ":" + (("0" + dt.getMinutes()).slice(-2)) + ":" + (("0" + dt.getSeconds()).slice(-2)) + ":" + (("0" + dt.getMilliseconds()).slice(-2));
setinterval(timer, 1000);
Modify the code like this
setInterval(function(){
var dt = new Date();
document.getElementById("datetime").innerHTML = (("0"+dt.getDate()).slice(-2)) +"."+ (("0"+(dt.getMonth()+1)).slice(-2)) +"."+(dt.getFullYear()) +" "+ (("0"+dt.getHours()).slice(-2)) +":"+ (("0"+dt.getMinutes()).slice(-2)) +":"+ (("0"+dt.getSeconds()).slice(-2)) +":"+ (("0"+dt.getMilliseconds()).slice(-2));
}, 1);
<div id="datetime">
</div>
This will also work
<!DOCTYPE html>
<html>
<head>
<script>
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
ref: https://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock
In a google-apps-script, I have an html form with two date inputs. I want to set the default values to be the prior week of the current day.
I cannot get the following scripts to work. Can anyone point out what I am doing wrong?
I am getting a "Object does not allow properties to be added or changed" error.
Code.gs:
function pickDates() {
var d = new Date();
var e = new Date();
d.setDate((d.getDate() - d.getDay() % 7) - 7);
e.setDate(e.getDate() - (e.getDay() + 1) % 7);
d = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
e = e.getFullYear() + '-' + (e.getMonth() + 1) + '-' + e.getDate();
var htmlB = HtmlService.createHtmlOutputFromFile('Pick Dates').setWidth(200).setHeight(200);
htmlB.d = d;
htmlB.e = e;
SpreadsheetApp.getUi().showModalDialog(htmlB, 'Select Dates');
}
Pick Dates.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form>
Start Date<br>
<input id="start" type="date" name="startDay">
<br><br> End Date<br>
<input id="end" type="date" name="endDay">
<br><br>
<input type="button" value="Submit" onclick="google.script.run
.withSuccessHandler(google.script.host.close)
.sendEmails(this.parentNode)" />
</form>
<script>
document.getElementById('start').value = d;
document.getElementById('end').value = e;
</script>
</body>
</html>
To evaluate() the dates in the template, you will need to use createTemplateFromFile(). The error is because the HtmlOutput object returned from createHtmlOutputFromFile() can not have properties added like htmlB.d = d;. You can use a html template with scriptlets instead
function pickDates() {
var d = new Date();
var e = new Date();
d.setDate((d.getDate() - d.getDay() % 7) - 7);
e.setDate(e.getDate() - (e.getDay() + 1) % 7);
d = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
e = e.getFullYear() + '-' + (e.getMonth() + 1) + '-' + e.getDate();
// create a template
var htmlB = HtmlService.createTemplateFromFile('Pick Dates');
htmlB.d = d;
htmlB.e = e;
// evaluate() returns HtmlOuput object
var modal_html = htmlB.evaluate().setWidth(200).setHeight(200);
SpreadsheetApp.getUi().showModalDialog(modal_html, 'Select Dates');
}
Pick Dates.html - add the printing scriptlets
...
<script>
document.getElementById('start').value = <?= d ?>;
document.getElementById('end').value = <?= e ?>;
</script>
</body>
So I'm making a countdown timer and I'm trying to figure out how to grab the values inputted through the form and put them in the display so the timer can count down from that.
Here's the (probably vastly wrong) JS function I wrote:
function changeTime() {
var h = parseInt(hrs.value);
var m = parseInt(mns.value);
var s = parseInt(scs.value);
if (h < 10) {
h = 0 + h;
};
if (m < 10) {
m = 0 + m;
};
if (s < 10) {
s = 0 + s;
};
$("#time").html() = h + ":" + m + ":" + s;
}
$("#change").click(function() {
changeTime();
})
Here's the form part of the HTML:
<form id="choose">
<input type="text" id="hrs" name="hrs" size="2" maxlength="2" placeholder="h"/>
<input type="text" id="mns" name="mns" size="2" maxlength="2" placeholder="m"/>
<input type="text" id="scs" name="scs" size="2" maxlength="2" placeholder="s"/>
</form>
Here's the whole fiddle. I know the alignment is off, but I'll fix it, I just want help with the JS. Thanks!
The html() setter should be work only if you added HTML string as the argument in the method.
$("#time").html( h + ":" + m + ":" + s );
Although you need to use string concatenation instead of Number addition.
if (h < 10) {
h = '0' + h;
//--^-^--- this should be string
};
I'm using modified code originally supplied by Google to make a transit trip planner form that uses Google Maps. I'd like the results to open in a new window/tab so the user doesn't have to leave the site (I realize this is a somewhat controversial usability issue, but this is at my client's behest, so...).
The code below uses target="_blank" in the tag - which seemed like the simplest solution - but that doesn't work in this instance - not sure why, but thought it may have something to do with the dynamically-built URL.
I tried several methods gleaned from previous similar questions on this site, the method below being one of them, as well as something along the lines of
myForm.setAttribute("target", "_blank");
but so far nothing has been successful.
Here's the code I'm using. Any suggestions would be greatly appreciated.
<script language="JavaScript" type="text/javascript">
// Edit the strings below this line
var startExample = "USC";
var endExample = "201 N Los Angeles St.";
var zip = "90012";
// End edit block
// Get and parse the user's current date/time
var date = new Date();
var isPM = false;
var currentTime = date.getHours();
var currentDate = "";
var amOption = '<option value="am">AM';
var pmOption = '<option value="pm">PM';
if(currentTime > 11)
isPM = true;
currentTime %= 12;
if(currentTime == 0)
currentTime = 12;
currentTime += ':';
if(date.getMinutes() < 10)
currentTime += '0';
currentTime += date.getMinutes();
if(isPM)
pmOption = '<option selected="true" value="pm">PM';
else
amOption = '<option selected="true" value="am">AM';
if(date.getMonth() < 9)
currentDate = '0';
currentDate += (date.getMonth() + 1) + '/';
if(date.getDate() < 10)
currentDate += '0';
currentDate += date.getDate() + '/' + date.getFullYear();
// Builds the destination URL
function buildURL() {
var loc = 'http://www.google.com/maps?ie=UTF8&f=d&';
for (var i = 0; (i < document.myForm.length - 1); i++) {
if(document.myForm[i].name == 'ampm')
continue;
if(document.myForm[i].name == 'time')
loc += document.myForm[i].name + '=' + document.myForm[i].value + document.myForm.ampm.value + '&';
else {
if(document.myForm[i].name == 'saddr')
loc += document.myForm[i].name + '=' + document.myForm[i].value + '+near+' + zip + '&';
else
loc += document.myForm[i].name + '=' + document.myForm[i].value + '&';
}
}
loc+='dirflg=r';
location.href=loc;
return true;
}
</script>
<form name="myForm" id="myForm" action="#" target="_blank">
<p>Powered by Google Maps</p>
<label for="saddr"><strong>Start</strong> e.g.
<script language="JavaScript" type="text/javascript">
document.write(startExample)
</script>
</label>
<input type="text" name="saddr" maxlength="2048" title="Enter the Origin Address" class="startend" />
<label for="daddr"><strong>End</strong> e.g.
<script language="JavaScript" type="text/javascript">document.write(endExample)</script></label>
<input type="text" name="daddr" maxlength="2048" title="Enter the Destination Address" class="startend" />
<div class="gadgetform-row">
<script language="JavaScript" type="text/javascript">
document.write('<div class="datewrapper">');
document.write('<label for="date"><strong>Date</strong></label><br />');
document.write('<input class="date" type="text" id="fdate" name="date" value="' + currentDate + '" maxlength="10" title="Enter the Date in MM/DD/YY format">');
document.write('</div>');
document.write('<div class="timewrapper">');
document.write('<label for="time"><strong>Time</strong></label><br />');
document.write('<input class="time" type="text" id="ftime" name="time" value="' + currentTime + '" maxlength="8" title="Enter the Time in HH:MM AM or PM format">');
document.write('</div>');
document.write('<div class="ampmwrapper">');
document.write(' <br />');
document.write('<select name="ampm" class="ampm">' + amOption + pmOption + '</select>');
document.write('</div>');
document.write('<div class="clear"></div>');
</script>
</div>
<div class="planby">
<label for="ttype"><strong>Plan by:</strong> </label
><select name="ttype">
<option value="dep">Departure Time </option>
<option value="arr">Arrival Time</option>
</select>
</div>
<a class="button" href="javascript:void();" onclick='return buildURL();'><span class="plan">Plan My Trip</span></a>
</form>
You can try using window.open instead. Here's a function that I created for opening child windows:
openChildWindowWithDimensions = function(url, width, height, showMenu, canResize, showScrollbars) {
var childWindow = window.open(url, "", "\"width=" + width + ",height=" + height + ",menubar=" + (showMenu ? "1" : "0") + ",scrollbars=" + (showScrollbars ? "1" : "0") + ",resizable=" + (canResize ? "1" : "0") + "\"");
if (childWindow){
childWindow.resizeTo(width, height); //IE9 dimensions bug
}
}
Add this function to your page, and at the end of your function that builds the URL, call it like this:
openChildWindowWithDimensions(loc, 800, 600, true, true, true);