array resetting itself javascript - javascript

i am just beginning javascript so i decided to make a program that accepts values from the user on a button click and stores them in an array of object and on click of another button show writes them to the innerHTML of a paragraph
<!DOCTYPE HTML>
<html>
<head>
<script>
var records = new Array();
var counter = 0;
var t = document.getElementById("show");
function record(name,age,cla)
{
this.name=name;
this.age=age;
this.cla=cla;
}
function add()
{
var r1 = new record(frm1.name.value,frm1.age.value,frm1.clas.value);
alert(r1.name);
records.push(r1);
alert(records[0].name);
}
function show()
{alert(records.length);
for(var i=counter;i<records.length;i++,counter++)
{
t.innerHTML+= records[i].name+" "+records[i].age+" "+records[i].cla+"<br>";
}
}
function clear()
{
t.innerHTML="";
counter=0;
}
</script>
</head>
<body>
<form id = "frm1" >
name : <input type = text id = "name">
age : <input type = text id = "age">
class : <input type = text id = "clas">
<button onclick= "add()">add</button>
<button onclick = "show()">show</button>
<button onclick = "clear()">clear</button>
</form><br>
<p id = "show"></p>
</body>
</html>
so after debugging it i found out that the element is added properly but whenever i call the show method the records.length shows 0 .. why is the array resetting itself ?

Three issues:
1) Your form is trying to submit when you click on one of your buttons and thus is causing the page to reload. When the page is reloaded, everything is reinitialized and thus the array is empty.
You can fix that by calling preventDefault() to prevent the default behavior of the button click.
2) You are calling document.getElementById("show") before the page has been parsed so it will always be null.
You will need to put that script element at the end of the page after the DOM has been loaded. You can actually put all your scripts at the end of the document.
3) Your clear() method name interferes with a predefined global symbol of the same name so you should change it to a different function name. This is one of the reasons why you generally want to avoid globally scoped symbols.
Here's a working demo: http://jsfiddle.net/jfriend00/ZvbS6/
Note: If you are using plain javascript, then you will have to deal with some browser differences. Older versions of IE don't support e.preventDefault(). See this prior answer for details.

Related

Script to play music on button click and disable button after specified time

I'm trying to use the onClick function to make a button play an audio file and then disable after a specified length of time (to line up with the end of the audio file). Basically I'm trying to set up a Mission Impossible-esque thing where, when the button is clicked, the audio file plays and at the end of the recording the button disables (the message "self-destructing"). I can get the file to play but I can't figure out how to get the button to disable using the script code. This is what I've got so far. I tried both document.getElementById("briefingButton").this.disabled="true" and document.getElementById("briefingButton").style.display="none" and neither works.
<p id="briefingButton"><input type="button" value="Click for briefing" onclick="playMusic(); disableButton()" />
<script>
function playMusic(){
var music = new Audio('/Users/devonhunt/Documents/ADVENTURE WEDDING/Mission briefings/dom mk1.mp3');
music.play();
}
setTimeout(function disableButton() {
document.getElementById("briefingButton").this.disabled="true";
}, 1080)
</script></p>
I'm not really familiar with how the HTMLMediaElement API works, but I can give you a general solution for your problem:
<p><input type="button" id="briefingButton" value="Click for briefing" onclick="playMusic()" /></p>
<script>
function playMusic() {
var music = new Audio('/Users/devonhunt/Documents/ADVENTURE WEDDING/Mission briefings/dom mk1.mp3');
music.play();
let timer = setTimeout(function () {
document.getElementById("briefingButton").disabled="true";
}, 1080)
}
</script>
You can do the actions you want in 1 function, so I got rid of "disableButton()" from the inline onClick property.
Your setTimeout function wasn't setup right. You have to put it inside of a variable (Ex: let timer = setTimeout(callback, time);) You were attempting to call the setTimeout callback function (disableButton()) directly, but you have to call the variable you set it to.
I put the setTimeout function inside of the playMusic() function. Now when you call the function, your music plays, and then setTimeout is activated, which will disable the button after 1080ms (assuming that's how long the music plays for).
You were trying to disable the button by typing element.THIS.disabled = true. You don't need the THIS word, that will throw up an error. Just element.disabled = true is good.
Your id selector was pointing to the p tag, so it was disabling the p tag and not the button. So I put the id inside of the button tag. Also I took the script out of the p tag and put it afterwards. It's just more conventional that way.
I wasn't able to test out the audio portion of the code, but this should work :)
Firstly, your named function disableButton isn't named in the global scope. It's sort of bizarre, but I couldn't tell you exactly what scope it's in; however, I can tell you that it's not global. Check here for more information on scopes.
So the first thing you need to do is remove your disable button from the timeout and have it in the same scope as playMusic.
Secondly, just use the disable button function to call setTimeout with the first argument being an anonymous function which disables the button, like so:
function disableButton() {
setTimeout(function () {
document.getElementById("briefingButton").this.disabled = "true";
}, 1080)
}
Thirdly, there is no "this" property on your input document object (we'll discuss more about this later), so it's best just to remove it, leaving us with:
document.getElementById("briefingButton").disabled = "true";
Fourthly, the value true is of the primitive data type Boolean in javascript, so you should simply remove the quotes and assign the value to true without the quotes leaving us with:
document.getElementById("briefingButton").disabled = true;
Lastly, your html is mistaken. Your id is on your <p> tag, so when you call document.getElementById, you end up trying to disable a <p> tag. You have to id your input tag if you want it to work correctly. As such, it should look like:
<input id="briefingButton" value="Click for briefing" onclick="playMusic(); disableButton()" />
One thing I'd like to mention in addition is that it's not typical convention to use a script tag within a p tag (although this is technically permissible. HTML is after all the wild west of markup languages). More usually, you'll see the script tags nested one level deep in the body tag under all the other tags.
Also, there is a button tag in html if you'd like to use that instead. That would look like this:
<button id="briefingButton"onclick="playMusic(); disableButton()">Click for briefing</button>
Furthermore, if you know that you want to disable it after the music has finished playing, you can just incorporate the setTimeout function call into your play music function and use the media duration as the timeout value like so:
function playMusic() {
var music = new Audio('/Users/devonhunt/Documents/ADVENTURE WEDDING/Mission briefings/dom mk1.mp3');
music.play();
setTimeout(function () {
document.getElementById("briefingButton").disabled = true;
}, music.duration * 1000) // times 1000 because it gives you the duration in seconds and setTimeout take milliseconds as an argument
}

Display Element count without button

Im trying display the count of the childnode in the html page, is there anyway I can display the count without using button onclick function, html page:
<span id="demo"></span> <button type ="button"onclick ="test()">click</button>
function getCount(){
var nodeToCount = document.getElementById("overall-page");
var questionCount = document.getElementsByClassName("survey-form");
document.getElementById("demo").innerHTML = questionCount.length;
console.log(questionCount.length);
}
There are many events you can use...
https://www.w3schools.com/js/js_events.asp
What do you want to achieve? it could run on window load? mouse hover over the area?

How to make a button click a button on a different page

I have a button on one html page, but when clicked I want it to activate a different button on a different html page. Is this possible?
This is only possible if the first page actually generates the second page (via window.open()). Otherwise, you won't have any way to access the document in the other window.
Here's an example:
var newWin = window.open("other page in my domain");
var otherButton = newWin.document.querySelector("selector to find button");
otherButton.click();
This solution will work though, but it requires passing a value from one page to another. It cannot link pages together. If you want that look into websockets.
Page 1
HTML
<button id="activate">Activate other page</button>
JavaScript
document.querySelector("#activate").addEventListener("click", function(){
location.href = "page2.html?button=activate"; //mind the querystring here.
});
Page 2
HTML
<button id="toactivate" disabled>disabled button</button>
JavaScript
var activateButton = location.search.slice(1); //querystring | get rid of the ?
activateButton.split(/&/);
activateButton.forEach(function(value){
var splitted = value.split("=");
if (splitted[0] == "button" && splitted[1] == "activate")
{
document.querySelector("#toactivate").removeAttribute("disabled");
}
});

How to make a button's onclick function in one webpage execute a function in another webpage without php

In my main html page, I have the following code:
<p class="text" id="time">00:00</p>
In my other html page, I have the following code:
<button onclick="resettime()">RESET TIME</button>
They both link to the same javascript page, which has the code:
function timeIncrement()
{
document.getElementById('time').innerHTML = +mins+":"+secs;
if(secs==60)
{
mins+=1;
secs = 0;
}
}
var timecheck = setInterval(timeIncrement,1000);
function resettime()
{
clearInterval(timecheck);
mins = 0;
secs = 0;
timecheck = setInterval(timeIncrement,1000);
}
Clicking the button doesn't reset the time to 0:0, so it doesn't work, so I was wondering if there's any way I can do this without going into php. I'm new to html/js, so sorry if this is a repeat, couldn't find a similar one.
Two html means two windows. if you want to execute script from one window to another window, you should have the other window's object and both window should have document.domain. for having reference of another window
in main html add the following 
<script>window.open("other.html");//other html will open automatically</script>
in other html, change the code to following
<button onclick="resettimeinMainHtml()">RESET TIME</button>
<script>function resettimeinMainHtml(){window.opener.resettime();// will reset in mail html}</script>

Assign value to Javascript variable

I am trying to assign value to javascript variable without refreshing page but its not working.
Consider example:
<head>
<script type="text/javascript">
var id='';
var source='';
function assignvalue(_id,_source){
//open div load in dialog box
id = _id;
source = _source;
}
</script>
</head>
<body>
<div id='load'></div>
<script>
_login.push(['login', 'callback_uri', 'http://localhost/Login/index/?source='+source+'&id='+id']);
</script>
</body>
In head define some variable globally and onclick of a tag I am opening div with load id and having global varible with new value.But new value is not assign to it below divs javascript.Any suggestion.
Thanks.
you are declaring two global variables id and source, but in your function definition you declare two local variables with the same name, so your desired changes to global variables are applied to local ones. Just rename the variables in the function definition.
For instance:
var id, source;
function assignvalue (_id, _source) {
id = _id;
source = _source;
}
Because the way you pass value cannot be
function assignvalue(id,source)
cause id and source in the function here will become local variable instead.
Please replace the variable in parsing to other name so that it work, i.e
function assignvalue(passID,passSource){
id = passID;
source = passSource;
console.log(id+" "+source);
}
then the global variable value will change.
You are declaring id and source twice: once in the global scope, and once as function parameters.
To overwrite the values of the global variables inside the function, you need to use a different name for the parameters.
Try
function assignvalue(_id, _source) {
id = _id;
source = _source;
}
To execute the _login function when the link is clicked, you could simply call it in assignValue:
function assignvalue(id, source) {
_login.push(['login', 'callback_uri', 'http://localhost/Login/index/?source='+source+'&id='+id']);
}
In that case, it wouldn't be a bad idea to rename the function assignvalue to login
Yes, whatever you have written is correct.
But when you click on an HyperLink it will automatically refreshes the page.
Here you want to disable that auto refresh when you click on the Hyper link.For that you could amend your code like this:
<html>
<head>
<script>
var id,source;
function assignValue(_id,_source){
id = _id;
source = _source;
alert(_id+" and also "+_source);
}
</script>
</head>
<body>
<script>
alert(id+" I am in Body "+source);
</script>
Hello
</body>
OR alternatively you can try this
<html>
<head>
<script>
var id,source;
function assignValue(_id,_source){
id = _id;
source = _source;
alert(_id+" and also "+_source);
return false;
}
</script>
</head>
<body>
<script>
alert(id+" I am in Body "+source);
</script>
Hello
</body>
Extra Info:
To override the default browser functionality, just you have to return false.
Not only here, almost you can apply this in many situations.
One such situation is disabling right click(simply) is just
oncontextmenu= return false;
and another such situation is disabling a KeyPress Event and so on.
So, you can apply this almost anywhere.

Categories

Resources