Loop a code n times in javascript, n determined by user input? - javascript

I'm trying to offer a text box in which the user can enter the size of the array to create, hit submit, then a prompt will appear that many times, each time asking for an integer to put in the array.
This is what I have so far:
http://codepen.io/sharryliang0730/pen/pRMqOm
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.onload = function() {
document.getElementById('ifYes').style.display = 'none';
document.getElementById('ifNo').style.display = 'none';
}
function yesnoCheck() {
if (document.getElementById('yesCheck').onclick) {
document.getElementById('ifYes').style.display = 'block';
document.getElementById('ifNo').style.display = 'none';
}
else if(document.getElementById('noCheck').onclick) {
document.getElementById('ifNo').style.display = 'block';
document.getElementById('ifYes').style.display = 'none';
}
}
var submit = document.getElementById('submit');
submit.onclick = function() {
getTheData() ;
}
function getTheData() {
var sizeInput = document.getElementById("sizeInput");
var inputValues = new Array();
for (var i = 0; i < sizeInput; i++){
inputValues.push(prompt('Enter the value'));
}
}
</script>
</head>
<body>
Please choose what you wanna do:<br>
<input type="button" onclick="javascript:yesnoCheck();" name="yesno" id="yesCheck" value="Create Array"/>
<input type="button" onclick="javascript:yesnoCheck();" name="yesno" id="noCheck"value="Search Array"/>
<br>
<div id="ifYes" style="display:none">
<br> Please input the size of the array.<br><br>
<input type="text" class="sizeInput" id="sizeInput" /> <br/><br>
<input type="button" name="submit" id="submit" value="Submit"/>
</div>
<div id="ifNo" style="display:none">
<div id="showInputValues">
</div>
EDIT: I added in the suggested code, but it is still not working. Am I missing something?

Your inputValues is empty. You need to add this:
var inputValues = new Array();
for (var i = 0; i < sizeInput; i++)
{
inputValues.push(prompt('Enter the value'));
}
it gives you an array like this: ["1", "2", "3"]
But if you want your array has int values do this:
for (var i = 0; i < 5; i++)
{
inputValues.push(parseInt(prompt('Enter the value')));//[1,2,3]
}
By your explanations var sizeInput = document.getElementById("sizeInput");
sizeInput is a number that user entered. If it is for example 5 and you want the array has [0,1,2,3,4] you need to do this:
for (var i = 0; i < sizeInput; i++)
{
inputValues.push(i);
}
You have many problems in your code, I edited all in code snippet below:
<head>
<script type="text/javascript">
window.onload = function ()
{
document.getElementById('ifYes').style.display = 'none';
document.getElementById('ifNo').style.display = 'none';
var submit = document.getElementById('submit');
submit.onclick = function ()
{
getTheData();
}
}
function yesnoCheck()
{
if (document.getElementById('yesCheck').onclick)
{
document.getElementById('ifYes').style.display = 'block';
document.getElementById('ifNo').style.display = 'none';
}
else if (document.getElementById('noCheck').onclick)
{
document.getElementById('ifNo').style.display = 'block';
document.getElementById('ifYes').style.display = 'none';
}
}
function getTheData()
{
var sizeInput = document.getElementById("sizeInput").value;
var inputValues = new Array();
for (var i = 0; i < sizeInput; i++)
{
inputValues.push(prompt('Enter the value'));
}
}
</script>
</head>
<body>
Please choose what you wanna do:<br>
<input type="button" onclick="javascript: yesnoCheck();" name="yesno" id="yesCheck" value="Create Array" />
<input type="button" onclick="javascript: yesnoCheck();" name="yesno" id="noCheck" value="Search Array" />
<br>
<div id="ifYes" style="display: none">
<br>
Please input the size of the array.<br>
<br>
<input type="text" class="sizeInput" id="sizeInput" />
<br />
<br>
<input type="button" onclick="javascript: loopFunction();" name="submit" id="submit" value="Submit" />
</div>
<div id="ifNo" style="display: none"></div>
<div id="showInputValues">
</div>
</body>

Related

Javascript multidimensional array loop from form inputs

I am having a problem with the array of an array. I need the function clickMe() to allow me to output an array such as [[1,1,1,1,1],[2,2,2,2,2],etc].
My problem is that right now the values come up as [1,1,1,1,1,2,2,2,2,2,etc]. I know a for loop inside a for loop would be the best way for this, but how would I get the inputs in sections of five?
Once I can figure this out, I should be able to pull from those arrays without any issues. I would prefer to keep this completely in Javascript.
var qNumber;
function onEnter() {
var qNumber = document.getElementsByName("numberBox")[0].value;
if(event.keyCode == 13) {
if (typeof(Storage) !== "undefined") {
localStorage.setItem("qNumber", qNumber);
console.log(qNumber + " stored successfully");
} else {
console.log("Sorry, your browser does not support Web Storage...");
}
var qID = document.getElementById("numBox");
var submitBtn = document.getElementById("submitButton");
var a = qNumber - 1;
var b = 0;
while (b < a) {
var formClone = document.getElementsByClassName("formBox")[0];
var listClone = formClone.cloneNode(true);
var text =b+2;
document.getElementById("forms").append(listClone);
b++;
}
return qID.parentNode.removeChild(qID);
}
return qNumber;
}
function clickMe() {
var q = localStorage.getItem("qNumber");
console.log(q);
var inputNow = [];
var allInputs = [];
var eachArray = [];
var inputNow = document.getElementsByTagName("input");
for(x=0; x < inputNow.length; x++) {
allInputs.push(inputNow[x].value);
console.log(allInputs);
}
localStorage.clear();
}
input{
display: block;
}
<div id="forms">
<span id="numBox">
<label for="numberBox">Number of Forms</label>
<input type="number" name="numberBox" onkeydown="onEnter()" />
</span>
<form id="formBox" name="formBox" action="#" onsubmit="return false;">
<label for="info1">Input 1:</label>
<input type="text" name="info1" />
<label for="info2">Input 2:
</label>
<input type="text" name="info2" />
<label for="info3">Input 3:
</label>
<input type="text" name="info3" />
<label for="info4">Input 4:
</label>
<input type="text" name="info4" />
<label for="info5">Input 5:
</label>
<input type="text" name="info5" />
</form>
</div>
<input type="submit" value="Submit" id="submitButton" onclick="clickMe()" />
<div id="content">
<span id="info1">input1</span>
<br/>
<span id="info2">input2</span>
<br/>
<span id="info3">input3</span>
<br/>
<span id="info4">input4</span>
<br/>
<span id="info5">input5</span>
</div>
You can always do something like:
var allInputs = [];
var groupInputs = [];
for (x=0; x < inputNow.length; x++) {
groupInputs.push(inputNow[x].value);
if (groupInputs.length === 5 || x === inputNow.length - 1) {
allInputs.push(groupInputs);
groupInputs = [];
}
}

HTML, JS - Display Loop's Output By Calling <div> From HTML To JS

I have a situation where user may insert the Total Quantity and also the Total Pass and Total Fail. I have created a function where when the number of Total Pass inserted, the loop (of entering the pass score) will run according to the iterations inputted.
However, I do not want to have the loop to display the line Enter The Score : in the JavaScript function. Therefore, I want the function to call a div from the HTML itself.
For example, I want the <div id="outputPass"><p>Enter the score : <input type="text" /></p></div> to be called in the loop function which I have created in the document.getElementById('btnPass').onclick = function().
I have inserted some comments in the code section.
document.getElementById('btnPass').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputPass').value);
var output = document.getElementById('outputPass');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Pass Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
item.innerHTML = "";
output.appendChild(item);
}
}
};
document.getElementById('btnFail').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputFail').value);
var output = document.getElementById('outputFail');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Fail Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
item.innerHTML = "";
output.appendChild(item);
}
}
};
function togglePass() {
var x = document.getElementById("passDiv");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
function toggleFail() {
var y = document.getElementById("failDiv");
if (y.style.display === "block") {
y.style.display = "none";
} else {
y.style.display = "block";
}
}
.display {
display: none;
}
<form method="post" name="form">
<p>Enter the quantity : <input type="text" id="quantity" name="quantity" /></p><br />
<input type="button" value="Pass" onclick="togglePass()">
<input type="button" value="Fail" onclick="toggleFail()">
<div id="passDiv" class="display">
<p>Enter Total Pass : <input type="text" id="inputPass" name="inputPass" />&nbsp<input type="button" value="Key In Score" id="btnPass" onclick="return validate();"></p><br />
<!--This Div-->
<div id="outputPass">
<p>Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
<br />
<div id="failDiv" class="display">
<p>Enter Total Fail : <input type="text" id="inputFail" />&nbsp<input type="button" value="Key In Score" id="btnFail"></p><br />
<!--This Div-->
<div id="outputFail">
<p>Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
</form>
You can make the following changes to achieve what you are looking for:
Initially we're giving an id of pscore/fscore (for pass and fail respectively) to the <p></p> tags and hiding them.
<p id="fscore" style="display:none">Enter the score : <input type="text" /></p>
We're accessing them in the javascript code in the form of variables pscore and fscore respectively. (Make sure they are declared globally outside)
var pscore = document.getElementById('pscore');
var fscore = document.getElementById('fscore');
Then in the iterations we can just make a clone of the pscore/fscore , give a class of pscore/fscore to the <p></p> tags and remove the id of pscore/score (to avoid duplicate IDs), changing the display to block and append it to the output container by using the following:
var cln = pscore.cloneNode(true);
cln.style.display="block";
cln.className ="pscore";
cln.removeAttribute("id");
item.appendChild(cln);
var cln = fscore.cloneNode(true);
cln.style.display="block";
cln.removeAttribute("id");
cln.className ="fscore";
item.appendChild(cln);
var pscore = document.getElementById('pscore');
var fscore = document.getElementById('fscore');
document.getElementById('btnPass').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputPass').value);
var output = document.getElementById('outputPass');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Pass Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
var cln = pscore.cloneNode(true);
cln.style.display = "block";
cln.className = "pscore";
cln.removeAttribute("id");
item.appendChild(cln);
output.appendChild(item);
}
}
};
document.getElementById('btnFail').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputFail').value);
var output = document.getElementById('outputFail');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Fail Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
var cln = fscore.cloneNode(true);
cln.style.display = "block";
cln.className = "fscore";
cln.removeAttribute("id");
item.appendChild(cln);
output.appendChild(item);
}
}
};
function togglePass() {
var x = document.getElementById("passDiv");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
function toggleFail() {
var y = document.getElementById("failDiv");
if (y.style.display === "block") {
y.style.display = "none";
} else {
y.style.display = "block";
}
}
.display {
display: none;
}
<form method="post" name="form">
<p>Enter the quantity : <input type="text" id="quantity" name="quantity" /></p><br />
<input type="button" value="Pass" onclick="togglePass()">
<input type="button" value="Fail" onclick="toggleFail()">
<div id="passDiv" class="display">
<p>Enter Total Pass : <input type="text" id="inputPass" name="inputPass" /> <input type="button" value="Key In Score" id="btnPass"></p><br />
<!--This Div-->
<div id="outputPass">
<p id="pscore" style="display:none">Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
<br />
<div id="failDiv" class="display">
<p>Enter Total Fail : <input type="text" id="inputFail" /> <input type="button" value="Key In Score" id="btnFail"></p><br />
<!--This Div-->
<div id="outputFail">
<p id="fscore" style="display:none">Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
</form>

How to add a checked checkbox element into Div dynamically?

I want to make a JavaScript function, which, after pressing a button, takes the list of checkbox elements with their content, checks all the checkboxes, creates a div element with these checkboxes and writes the result to the HTML form.
Here is my code:
function confirmDrivers() {
$('#selectedList').find('.chk').prop("checked", true);
var list = document.getElementById('selectedList').getElementsByTagName("li");
var myForm = document.getElementById('formInput');
var text = "<strong>Selected Drivers: </strong> <br><br>";
var myDiv = document.createElement("div");
myDiv.setAttribute("id","selectedInputDrivers");
myDiv.style.overflowY = "auto";
myDiv.style.maxHeight = "100px";
myDiv.style.maxWidth = "250px";
for (i = list.length - 1; i >= 0; i--) {
myDiv.innerHTML = list[i].innerHTML+'<br>'+myDiv.innerHTML;
}
$("formInput").find('.chk').prop("checked", true);
myForm.innerHTML = myDiv.outerHTML + myForm.innerHTML;
myForm.innerHTML = text + myForm.innerHTML;
}
Here is the HTML Div element with the list of checkbox elements. They also appear dynamically. Initially, Div is empty.
<div id = "selectedList" class = "col" style=" max-height:200px; max-width:500px;display: inline-block; background:#A8D9F1; overflow-y:auto">
<strong style="margin-right:10px">Selected List of Drivers</strong>
<input type="button" style="margin-right:10px" value="Remove All" name="removeAllDr" onclick="removeAllDrivers()" />
<input type="button" id="confirmD" value="Confirm" name="confirm" onclick="confirmDrivers()" />
<br><br>
</div>
And this is the HTML form, where I want my result to appear:
<form id="formInput">
</form>
The problem here is that it checks all the checkboxes in my list, but in the resulting HTML form they appear unchecked again. What is wrong with it? Thank you
Besides replacing prop() to attr() as Rik Lewis correctly recommended you can alternately put the line
$("formInput").find('.chk').prop("checked", true);
at the bottom of the function and add the # character in front the selector id like this:
function confirmDrivers() {
$('#selectedList').find('.chk').prop("checked", true);
var list = document.getElementById('selectedList').getElementsByTagName("li");
var myForm = document.getElementById('formInput');
var text = "<strong>Selected Drivers: </strong> <br><br>";
var myDiv = document.createElement("div");
myDiv.setAttribute("id","selectedInputDrivers");
myDiv.style.overflowY = "auto";
myDiv.style.maxHeight = "100px";
myDiv.style.maxWidth = "250px";
for (i = list.length - 1; i >= 0; i--) {
myDiv.innerHTML = list[i].innerHTML+'<br>'+myDiv.innerHTML;
}
myForm.innerHTML = myDiv.outerHTML + myForm.innerHTML;
myForm.innerHTML = text + myForm.innerHTML;
$("#formInput").find('.chk').prop("checked", true);
}
function confirmDrivers() {
$('#selectedList').find('.chk').prop("checked", true);
var list = document.getElementById('selectedList').getElementsByTagName("li");
var myForm = document.getElementById('formInput');
var text = "<strong>Selected Drivers: </strong> <br><br>";
var myDiv = document.createElement("div");
myDiv.setAttribute("id", "selectedInputDrivers");
myDiv.style.overflowY = "auto";
myDiv.style.maxHeight = "100px";
myDiv.style.maxWidth = "250px";
for (i = list.length - 1; i >= 0; i--) {
myDiv.innerHTML = list[i].innerHTML + '<br>' + myDiv.innerHTML;
}
myForm.innerHTML = myDiv.outerHTML + myForm.innerHTML;
myForm.innerHTML = text + myForm.innerHTML;
$("#formInput").find('.chk').prop("checked", true);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selectedList" class="col" style=" max-height:200px; max-width:500px;display: inline-block; background:#A8D9F1; overflow-y:auto">
<strong style="margin-right:10px">Selected List of Drivers</strong>
<input type="button" style="margin-right:10px" value="Remove All" name="removeAllDr" onclick="removeAllDrivers()" />
<input type="button" id="confirmD" value="Confirm" name="confirm" onclick="confirmDrivers()" />
<br>
<br>
<ul>
<li>
<input type="checkbox" class="chk" value="test" />
</li>
<li>
<input type="checkbox" class="chk" value="test" />
</li>
<ul>
</div>
<form id="formInput">
</form>
<div id="cblist">
<input type="checkbox" value="first checkbox" id="cb1" /> <label for="cb1">first checkbox</label>
</div>
<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />
<script type="text/javascript">
$(document).ready(function() {
$('#btnSave').click(function() {
addCheckbox($('#txtName').val());
});
});
function addCheckbox(name) {
var container = $('#cblist');
var inputs = container.find('input');
var id = inputs.length+1;
var html = '<input type="checkbox" id="cb'+id+'" value="'+name+'" /> <label for="cb'+id+'">'+name+'</label>';
container.append($(html));
}
</script>

radio button only changes value when double clicked?

In my code I have five radio buttons with one set checked by default. When I click on a radio button the function setMode() is called but the test to check which button is checked fails.
When the same radio button is clicked a second time setMode() is called the test will return true.
The test is if(document.getElementById("rcool").checked)
I have tried changing the mouse events and the test eg. .checked=="true" and .checked=="checked".
I have searched and only found similar topics in jQuery which I am unfamiliar with so could not make sense of them.
I am using Firefox 47.0 and have checked for errors using Firebug 2.0.17.
I am not very sure how to use Firebug and don't know what to try next.
Any help or comments are greatly appreciated.
var options = ["power=off","mode=heat","temp=20"];
var temp = 20;
function power() {
var pwr = document.getElementById("powerBtn");
var pwrtxt;
if(pwr.innerHTML=="OFF"){
pwrtxt = "power=on";
pwr.innerHTML = "ON";
}
else {
pwrtxt = "power=off";
pwr.innerHTML = "OFF";
}
options[0] = pwrtxt;
document.getElementById("textOutput").value = options;
}
function setMode(){
if(document.getElementById("rheat").checked)
options[1] = "mode=heat";
if(document.getElementById("rcool").checked)
options[1] = "mode=cool";
if(document.getElementById("rdry").checked)
options[1] = "mode=dry";
if(document.getElementById("rauto").checked)
options[1] = "mode=auto";
if(document.getElementById("recono").checked)
options[1] = "mode=econo";
document.getElementById("textOutput").value = options;
}
function updateTemp(){
var tempString = "temp=";
options[2] = tempString.concat("",temp);
document.getElementById("textOutput").value = options;
}
function increaseTemp(){
temp += 1;
if(temp>31) {
temp = 31;
}
updateTemp();
}
function decreaseTemp(){
temp -= 1;
if(temp < 16){
temp = 16;
}
updateTemp();
}
function stopTime(){
}
function startTime(){
}
function incTime(){
}
function decTime(){
}
<!DOCTYPE html>
<html>
<body>
<button type="button" id="powerBtn" onmouseup="power()">OFF</button>
<button type="button" id="increase" onmouseup="increaseTemp()">Up</button>
<button type="button" id="decrease" onmouseup="decreaseTemp()">Down</button>
<br>
<input type="radio" id="rheat" name="mode" onmouseup="setMode()" value="heat" checked="checked">HEAT<br>
<input type="radio" id="rcool" name="mode" onmouseup="setMode()" value="cool">COOL<br>
<input type="radio" id="rdry" name="mode" onmouseup="setMode()" value="dry">DRY<br>
<input type="radio" id="rauto" name="mode" onmouseup="setMode()" value="auto">AUTO<br>
<input type="radio" id="recono" name="mode" onmouseup="setMode()" value="econo">ECONOCOOL<br>
<br>
<button type="button" id="stopTmr" onmouseup="stopTime()">Stop Time</button>
<button type="button" id="startTimer" onmouseup="startTime()">Start Timer</button>
<br>
<button type="button" id="incTime" onmouseup="incTime()">Increase Time</button>
<button type="button" id="decTime" onmouseup="decTime()">Decrease Time</button>
<form action="action_page.php">
<textarea id="textOutput" name="message" rows="10" cols="30"></textarea>
<br>
<input type="submit">
</form>
</body>
</html>
To launch a function when a radio button is clicked, you must use onchange event, not onclick/onmouseup. onchange gracefully wait for the radio button to be effectively clicked/updated before calling the function.
var options = ["power=off","mode=heat","temp=20"];
var temp = 20;
window.onload=function(){document.getElementById("textOutput").value = options;}
function power() {
var pwr = document.getElementById("powerBtn");
var pwrtxt;
if(pwr.innerHTML=="OFF"){
pwrtxt = "power=on";
pwr.innerHTML = "ON";
}
else {
pwrtxt = "power=off";
pwr.innerHTML = "OFF";
}
options[0] = pwrtxt;
document.getElementById("textOutput").value = options;
}
function setMode(){
if(document.getElementById("rheat").checked)
options[1] = "mode=heat";
if(document.getElementById("rcool").checked)
options[1] = "mode=cool";
if(document.getElementById("rdry").checked)
options[1] = "mode=dry";
if(document.getElementById("rauto").checked)
options[1] = "mode=auto";
if(document.getElementById("recono").checked)
options[1] = "mode=econo";
document.getElementById("textOutput").value = options;
}
function updateTemp(){
var tempString = "temp=";
options[2] = tempString.concat("",temp);
document.getElementById("textOutput").value = options;
}
function increaseTemp(){
temp += 1;
if(temp>31) {
temp = 31;
}
updateTemp();
}
function decreaseTemp(){
temp -= 1;
if(temp < 16){
temp = 16;
}
updateTemp();
}
function stopTime(){
}
function startTime(){
}
function incTime(){
}
function decTime(){
}
<!DOCTYPE html>
<html>
<body>
<button type="button" id="powerBtn" onmouseup="power()">OFF</button>
<button type="button" id="increase" onmouseup="increaseTemp()">Up</button>
<button type="button" id="decrease" onmouseup="decreaseTemp()">Down</button>
<br>
<input type="radio" id="rheat" name="mode" onchange="setMode()" value="heat" checked="checked">HEAT<br>
<input type="radio" id="rcool" name="mode" onchange="setMode()" value="cool">COOL<br>
<input type="radio" id="rdry" name="mode" onchange="setMode()" value="dry">DRY<br>
<input type="radio" id="rauto" name="mode" onchange="setMode()" value="auto">AUTO<br>
<input type="radio" id="recono" name="mode" onchange="setMode()" value="econo">ECONOCOOL<br>
<br>
<button type="button" id="stopTmr" onmouseup="stopTime()">Stop Time</button>
<button type="button" id="startTimer" onmouseup="startTime()">Start Timer</button>
<br>
<button type="button" id="incTime" onmouseup="incTime()">Increase Time</button>
<button type="button" id="decTime" onmouseup="decTime()">Decrease Time</button>
<form action="action_page.php">
<textarea id="textOutput" name="message" rows="10" cols="30"></textarea>
<br>
<input type="submit">
</form>
</body>
</html>
Normally I put listeners on those radio buttons and identify them when they are clicked. It seems you prefer the old school way of doing it so I didn't change much in your code but added a paramter in your setMode() function called mode. Basically the mode is already defined when setMode() is called so you don't have to check each radio button anymore. switch() here can assign relative value to options[1] according to mode. Have a go with it and good luck.
var options = ["power=off","mode=heat","temp=20"];
var temp = 20;
function power() {
var pwr = document.getElementById("powerBtn");
var pwrtxt;
if(pwr.innerHTML=="OFF"){
pwrtxt = "power=on";
pwr.innerHTML = "ON";
}
else {
pwrtxt = "power=off";
pwr.innerHTML = "OFF";
}
options[0] = pwrtxt;
document.getElementById("textOutput").value = options;
}
function setMode( mode ){
switch ( mode ) {
case 'rheat':
options[1] = "mode=heat";
break;
case 'rcool':
options[1] = "mode=cool";
break;
case 'rdry':
options[1] = "mode=dry";
break;
case 'rauto':
options[1] = "mode=auto";
break;
case 'recono':
options[1] = "mode=econo";
break;
}
document.getElementById("textOutput").value = options;
}
function updateTemp(){
var tempString = "temp=";
options[2] = tempString.concat("",temp);
document.getElementById("textOutput").value = options;
}
function increaseTemp(){
temp += 1;
if(temp>31) {
temp = 31;
}
updateTemp();
}
function decreaseTemp(){
temp -= 1;
if(temp < 16){
temp = 16;
}
updateTemp();
}
function stopTime(){
}
function startTime(){
}
function incTime(){
}
function decTime(){
}
<button type="button" id="powerBtn" onmouseup="power()">OFF</button>
<button type="button" id="increase" onmouseup="increaseTemp()">Up</button>
<button type="button" id="decrease" onmouseup="decreaseTemp()">Down</button>
<br>
<input type="radio" id="rheat" name="mode" onmouseup="setMode('rheat')" value="heat" checked="checked">HEAT<br>
<input type="radio" id="rcool" name="mode" onmouseup="setMode('rcool')" value="cool">COOL<br>
<input type="radio" id="rdry" name="mode" onmouseup="setMode('rdry')" value="dry">DRY<br>
<input type="radio" id="rauto" name="mode" onmouseup="setMode('rauto')" value="auto">AUTO<br>
<input type="radio" id="recono" name="mode" onmouseup="setMode('recono')" value="econo">ECONOCOOL<br>
<br>
<button type="button" id="stopTmr" onmouseup="stopTime()">Stop Time</button>
<button type="button" id="startTimer" onmouseup="startTime()">Start Timer</button>
<br>
<button type="button" id="incTime" onmouseup="incTime()">Increase Time</button>
<button type="button" id="decTime" onmouseup="decTime()">Decrease Time</button>
<form action="action_page.php">
<textarea id="textOutput" name="message" rows="10" cols="30"></textarea>
<br>
<input type="submit">
</form>

how to make a button appear only when another button is clicked through basic JS

im new at this.So, what I want is to hide the RESET button when the clock is working and it should appear when the clock is stoped.same with STOP button that it must only appear when the clock is working.This all must be done with simple and basic Java Script.I dont know about Jquery.
<script language="javascript">
var t1;
var t2;
var t3;
function fn_sample() {
document.frm.txtS.value = parseInt(document.frm.txtS.value) + 1;
t1 = document.frm.txtS.value;
if(t1>60){
document.frm.txtS.value = 0;
fn_incMin();
}
window.setTimeout("fn_sample()", 1000);
}
function fn_incMin() {
document.frm.txtM.value = parseInt(document.frm.txtM.value) + 1;
t2 = document.frm.txtM.value;
if(t2>60){
document.frm.txtM.value = 0;
fn_incHrs();
}
window.setTimeout("fn_incMin()", 60000);
}
function fn_incHrs() {
document.frm.txtH.value = parseInt(document.frm.txtH.value) + 1;
t3 = document.frm.txtH.value;
window.setTimeout("fn_incHrs()", 3600000);
}
function fn_stop() {
window.clearTimeout(t1);
window.clearTimeout(t2);
window.clearTimeout(t3);
}
function fn_reset() {
document.frm.txtS.value = 0;
document.frm.txtM.value = 0;
document.frm.txtH.value = 0;
}
</script>
</head>
<body>
<form name="frm">
<input type="text" name="txtH" value="0" size="2"/>
<input type="text" name="txtM" value="0" size="2"/>
<input type="text" name="txtS" value="0" size="2"/>
<br /><br />
<input type="button" value="Start" onclick="fn_sample();" />
<input type="button" value="Stop" onclick="fn_stop();" />
<input type="button" value="Reset" onclick="fn_reset();" />
</form>
</body>
You could do like this
<input type="button" value="Start" onclick="fn_sample();this.form.reset.style.display='none'" />
<input type="button" value="Stop" onclick="fn_stop();this.form.reset.style.display='inline'" />
<input type="button" value="Reset" name='reset' onclick="fn_reset();" />
or you coud also use the disable property
<input type="button" value="Start" onclick="fn_sample();this.form.reset.disabled=true" />
<input type="button" value="Stop" onclick="fn_stop();this.form.reset.disabled=false" />
<input type="button" value="Reset" name='reset' onclick="fn_reset();" />
Basically, you'd want to have a onclick property on the buttons like this:
var stopClicked = function(){
document.getElementById("stop").style.display = "none";
document.getElementById("reset").style.display = "";
}
var resetClicked = function(){
document.getElementById("stop").style.display = "";
document.getElementById("reset").style.display = "none";
}
<button onclick='stopClicked()' id='stop'>Stop</button>
<button onclick='resetClicked()' id='reset'>Reset</button>
It's not pretty, but help you undestand whats happends
<script language="javascript">
var t1;
var t2;
var t3;
var st1, st2, st3;
function fn_sample() {
document.getElementById('reset').style.display = 'none';
document.getElementById('start').style.display = 'none';
document.getElementById('stop').style.display = 'inline-block';
running = true;
document.frm.txtS.value = parseInt(document.frm.txtS.value) + 1;
t1 = document.frm.txtS.value;
if(t1>60){
document.frm.txtS.value = 0;
fn_incMin();
}
st1 = window.setTimeout("fn_sample()", 1000);
}
function fn_incMin() {
document.frm.txtM.value = parseInt(document.frm.txtM.value) + 1;
t2 = document.frm.txtM.value;
if(t2>60){
document.frm.txtM.value = 0;
fn_incHrs();
}
st2 = window.setTimeout("fn_incMin()", 60000);
}
function fn_incHrs() {
document.frm.txtH.value = parseInt(document.frm.txtH.value) + 1;
t3 = document.frm.txtH.value;
st3 = window.setTimeout("fn_incHrs()", 3600000);
}
function fn_stop() {
document.getElementById('reset').style.display = 'inline-block';
document.getElementById('start').style.display = 'inline-block';
document.getElementById('stop').style.display = 'none';
window.clearTimeout(st1);
window.clearTimeout(st2);
window.clearTimeout(st3);
}
function fn_reset() {
document.frm.txtS.value = 0;
document.frm.txtM.value = 0;
document.frm.txtH.value = 0;
}
</script>
</head>
<body>
<form name="frm">
<input type="text" name="txtH" value="0" size="2"/>
<input type="text" name="txtM" value="0" size="2"/>
<input type="text" name="txtS" value="0" size="2"/>
<br /><br />
<input id="start" type="button" value="Start" onclick="fn_sample();"style="display:inline-block" />
<input id="stop" type="button" value="Stop" onclick="fn_stop();" style="display:none" />
<input id="reset" type="button" value="Reset" onclick="fn_reset();" style="display:inline-block" />
</form>
</body>
What is inside:
variables st1, st2, st3 are handlers to setTimeout (in your code STOP button doesn't work)
window.setTimeout returns handler to use with clearTimeout
all fields have style proporty which shows or hide buttons on start
document.getElementById('stop') gets element and style.display = 'inline-block'; sets visible on element or hide to hide element
on Start show some buttons and hide unnecessary, on Stop show others and hide unnecessary.
And thats all. In pure JS. this is fiddle to test it: https://jsfiddle.net/6qz30eae/

Categories

Resources