limit click button in html - javascript

I am trying to limit a button that can be clicked only 5 times to add radio button. After 5 times adding radio button, it will be disabled. What is the javascript code for this matter? I only able to disable it once after it is clicked. Below is the code
html
<input type ='button' id="id" onClick="a();">
<div id='a'></div>
javascript
function a(){
document.getElementById('a').innerHTML += "<input type='radio'>";
document.getElementById("id").disabled=true;
}

Place a global counter and play with it
var counter=0;
function a(){
if(counter<5){
document.getElementById('a').innerHTML += "<input type='radio'>";
counter++;
}
else{
document.getElementById("id").disabled=true;
}
}

A global variable for amount of times clicked will work:
var clicked = 0;
function a(){
document.getElementById('a').innerHTML += "<input type='radio'>";
clicked++; //increment
if (clicked == 5)
document.getElementById("id").disabled=true;
}

try this:
var counter = 1;
function a(){
if(counter >= 5) {
document.getElementById("id").disabled=true;
return false;
}
document.getElementById('a').innerHTML += "<input type='radio'>";
counter++
}

This is what you need:
var counter = 0;
function a ()
{
if (counter++ < 5)
document.getElementById('a').innerHTML += "<input type='radio'>";
else
document.getElementById('id').disabled = true;
}

You can count the radio buttons
<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Add 5</title>
<style>
input[disabled]{text-decoration:line-through;color:white;}
</style>
<script>
function add5(){
var radio,
btn= document.getElementById('add_radio'),
pa= document.getElementById('radioDiv'),
R= pa.querySelectorAll('[type=radio]');
if(R.length<5){
radio= document.createElement('input');
radio.type='radio';
pa.appendChild(radio);
}
else btn.disabled= 'disabled';
}
</script>
</head>
<body>
<p>
<input type ='button' id="add_radio" value="Add Radio"onClick="add5();">
</p>
<div id='radioDiv'></div>
</p>
</body>
</html>

Related

Hide AND unhide a <div> or <form> while executing code (progress bar a.o.)

the goal is to hide a form, do some stuff and unhide the form again. For example with this code for a progress bar I thought to do the following but the hiding/unhiding doesn't work. I'm probably overseeing something obvious.
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Progress Bar Demo</title>
<script>
var button;
var count;
var countmax;
var progressbar;
var timerID;
function start(max) {
show_div();
button = document.getElementById("button");
count = 0;
countmax = max;
progressbar = document.getElementById("bar");
progressbar.max = countmax;
timerID = setInterval(function(){update()},10);
show_div();
}//end function
function update() {
button.innerHTML = "Counting to " + countmax;
count = count + 100;
progressbar.value = count;
if (count >= countmax) {
clearInterval(timerID);
button.innerHTML = "Ready";
progressbar.value = 0;
}//end if
}//end function
function show_div() {
var x = document.getElementById("do_you_see_me?");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}//end function
</script>
</head>
<body>
<div id="do_you_see_me?" style="display: block";>Hi there!</div>
<p>
<button onclick="start(4321)" id="button" style="font-size:18px;">Ready</button><br>
<br>
<progress id="bar" value="0"></progress>
</p>
</body>
</html>
you can hide and unhide it. the problem with your code is when you trigger ready buton it will hide and then unhide the code automatically. this is becuase setInterval() function is asynchronious function. then you need call show_div() function inside the setInterval().
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Progress Bar Demo</title>
<script>
var button;
var count;
var countmax;
var progressbar;
var timerID;
function start(max) {
hide_div();
button = document.getElementById("button");
count = 0;
countmax = max;
progressbar = document.getElementById("bar");
progressbar.max = countmax;
timerID = setInterval(function()
{
update()
if(count>=countmax)
{
show_div();
}
},10);
}//end function
function update() {
button.innerHTML = "Counting to " + countmax;
count = count + 100;
progressbar.value = count;
if (count >= countmax) {
clearInterval(timerID);
button.innerHTML = "Ready";
progressbar.value = 0;
}//end if
}//end function
function show_div() {
document.getElementById("do_you_see_me?").style.display="block";
}//end function
function hide_div()
{
document.getElementById("do_you_see_me?").style.display="none";
}
</script>
</head>
<body>
<div id="do_you_see_me?" style="display: block";>Hi there!</div>
<p>
<button onclick="start(4321)" id="button" style="font-size:18px;">Ready</button><br>
<br>
<progress id="bar" value="0"></progress>
</p>
</body>
</html>
i hope this will fix your problem.

How to type text in HTML

I'm looking to get the HTML page to type out some text when you visit said page, as if someone behind the screen was using a keyboard even though no one is. I understand this may require the use of the <script> tag.
What I have so far
<html>
<head>
<title>Happy Valentine</title>
<style type="text/css">>
body {
background: black url("http://www.robodesign.ro/files/gallery/original/love_bites.jpg");
background-repeat: repeat;
background-position: center;
background-attachment: fixed;
}
</style>
</head>
<body onload=writetext() onLoad="setTimeout('delayer()', 2000)">
<p align=center></p>
<script language=JavaScript>
msg = new Array(); //strings written in screen
msg[0] = "Blah with html";
text1 = ""; //the same as text2, only the last character is highlighted.
text2 = ""; //current string, which will be written.
count = 0; //char index in string text
count2 = 0; //number of strings
text = msg[0].split(""); //text - string written
function writetext() { //show strings above on screen
text1 = text2 + "<font color='#FFFFFF'>" + text[count] + "</font>";
text2 += text[count];
document.all["nothing"].innerHTML = text1; //where to write
if (count < text.length-1){
count++;
setTimeout('writetext()', 34);
}
else { //if this string is written, get the new string
count = 0;
if (count2 != 14) { //write 14 strings
count2++;
text2 += ""; //a new line
text = eval('msg['+count2+'].split("")') //get the new string to text
setTimeout('writetext()', 1);
}
}
}
</script>
<script language="JavaScript">
function disableselect(e){
return false
}
function reEnable(){
return true
}
//if IE4+
document.onselectstart=new Function ("return false")
document.oncontextmenu=new Function ("return false")
//if NS6
if (window.sidebar){
document.onmousedown=disableselect
document.onclick=reEnable
}
</script>
</body>
</html>
For whatever reason, I can't get this to work and I can't establish why ._. I've been looking it over for a good few hours now.
your code have some errors for example:
setTimeout(writetext,34)
//count =0 inside the function make an non ending loop
i modified your code :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Happy Valentine</title>
<script>
msg1 = "Blah blah with html";
msg2 = " Blah with html";
count = 0;
count2 = 0;
function writetext() {
if (count < msg1.length){
document.getElementById("text").innerHTML += msg1.charAt(count);
count++;
setTimeout(writetext, 50);
}
else {
if (count2 < 14){
document.getElementById("text").innerHTML += msg2.charAt(count2);
count2++;
setTimeout(writetext, 50);
}
}
}
</script>
</head>
<body>
<button onclick="writetext()">Click me</button>
<p id="text"></p>
</body>
</html>
You can use this code and adapt it to what you need.
<!DOCTYPE html>
<html>
<body>
<h1>Typewriter</h1>
<p id="demo"></p>
<script>
var i = 0;
var txt = 'Lorem ipsum dummy text blabla. af \n af';
var speed = 50;
document.onload=typeWriter()
function typeWriter() {
if (i < txt.length) {
document.getElementById("demo").innerHTML += txt.charAt(i).replace("\n","<br>");
i++;
setTimeout(typeWriter, speed);
}
}
</script>
</body>
</html>
And your original code, tweaked to work:
<html>
<head>
<title>Happy Valentine</title>
<style type="text/css">
body {
background: black url("http://www.robodesign.ro/files/gallery/original/love_bites.jpg");
background-repeat: repeat;
background-position: center;
background-attachment: fixed;
}
</style>
</head>
<body onload=writetext() onLoad="setTimeout('delayer()', 2000)">
<p align=center id="printto"></p>
<script>
msg = new Array(); //strings written in screen
msg[0] = "Blah with html \n Nextline";
text1 = ""; //the same as text2, only the last character is highlighted.
text2 = ""; //current string, which will be written.
count = 0; //char index in string text
count2 = 0; //number of strings
text = msg[0].split(""); //text - string written
function writetext() { //show strings above on screen
text1 = text2 + "<font color='#FFFFFF'>" + text[count] + "</font>";
text2 += text[count];
document.getElementById("printto").innerHTML = text1.replace("\n","<br>"/*seamles neqlining*/); //where to write
if (count < text.length-1){
count++;
setTimeout('writetext()', 34);
}
else { //if this string is written, get the new string
count = 0;
if (count2 != 14) { //write 14 strings
count2++;
text2 += ""; //a new line
text = eval('msg['+count2+'].split("")') //get the new string to text
setTimeout('writetext()', 1);
}
}
}
</script>
<script>
function disableselect(e){
return false
}
function reEnable(){
return true
}
//if IE4+
document.onselectstart=new Function ("return false")
document.oncontextmenu=new Function ("return false")
//if NS6
if (window.sidebar){
document.onmousedown=disableselect
document.onclick=reEnable
}
</script>
</body>
</html>

Trying to print out a input text the number of times the user wrote in the secound input using a while loop

I have two input fields and a button. When the user clicks the button, I want it to display the text the user wrote in the first input the amount of times the user wrote in the second input.
I understand you have to use a while loop for this. What am I doing wrong here?
<!DOCTYPE html>
<html>
<head>
<title>While Loop</title>
<script type="text/javascript">
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
var inputOne = document.getElementById("txtBox").value;
var inputTwo = document.getElementById("numBox").value;
while (inputOne < inputTwo) {
text += inputOne;
inputOne++;
}
document.getElementById("showCode").innerHTML = text;
}
</script>
</head>
<body>
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
</body>
</html>
Since inputOne is a text, you cannot increment it (you can't do inputOne++), instead, use another variable, let's call it i, to control the while loop:
window.onload = btn;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
var inputOne = document.getElementById("txtBox").value;
var inputTwo = document.getElementById("numBox").value;
var i=1; // to control the loop
while (i <= inputTwo) { // i goes from 1 to inputTwo
text += inputOne;
i++;
}
document.getElementById("showCode").innerHTML = text;
}
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
This is my solution
<!DOCTYPE html>
<html>
<head>
<title>While Loop</title>
<script type="text/javascript">
window.onload = btn;
var count = 0;
function btn() {
document.getElementById("btn").onclick = showText;
}
function showText() {
var text = "";
console.log("Text: "+text);
var inputOne = document.getElementById("txtBox").value;
console.log("Input One: "+inputOne);
var inputTwo = document.getElementById("numBox").value;
console.log("Input 2: "+inputTwo);
count=count+1;
console.log("Times: "+count);
document.getElementById("numBox").value = count;
document.getElementById("showCode").innerHTML = text;
}
</script>
</head>
<body>
<input type="text" id="txtBox"><br/>
<input type="number" id="numBox"><br/>
<button type="button" id="btn">Click Me!</button>
<p id="showCode"></p>
</body>
</html>
Instead of the while loop you can use a for loop like this:
for( let i = inputTwo; i>0; i--) {
text += inputOne;
}

HTML Button Count

Im trying to implement a logic whereby each time I click the button the count alternates between 1 and 0. In the following code the count is always 0 as each time I press the button the function sets the count to 0. Please help me out and thanks in advance
<html>
<head>
<script type="text/javascript">
function main(){
var button = document.getElementById('button');
count = 0;
if(button.onclick && count == 0){
alert(count);
count = 1;
}
else if(button.onclick && count == 1){
alert(count);
count = 0;
}
}
</script>
</head>
<body>
<button type="button" id="button" onclick="main()">Click Me!</button>
</body>
</html>
Declare count variable at global scope.
<html>
<head>
<script type="text/javascript">
var count = 0;
function main(){
var button = document.getElementById('button');
if(button.onclick && count == 0){
alert(count);
count = 1;
}
else if(button.onclick && count == 1){
alert(count);
count = 0;
}
}
</script>
</head>
<body>
<button type="button" id="button" onclick="main()">Click Me!</button>
</body>
</html>
Declare the button in global scope. And use the bitwise operator for toggling between 0 and 1 like this..
<script type="text/javascript">
var count = 0; //global scope
function main(){
var button = document.getElementById('button');
if(button.onclick){
alert(count);
count ^= 1; //bitwise operator
}
}
</script>
^ (Bitwise XOR) as a I/O toggler
each time you click the button, main() is called. and each time you call main() you're setting count to 0 to start. Place count outside your function scope.
I agree with Ataur's answer but you might want to consider a bool for this use case as best practise.
<html>
<head>
<script type="text/javascript">
var buttonIsOn = true;
function main(){
var button = document.getElementById('button');
if(button.onclick && buttonIsOn){
alert("turning button off");
buttonIsOn = false;
}
else { // no need to check again if using bool
alert("turning button on");
buttonIsOn = true;
}
}
</script>
</head>
<body>
<button type="button" id="button" onclick="main()">Click Me!</button>
</body>
</html>
You should set the count to 0 outside of the function.
<html>
<head>
<script type="text/javascript">
var count = 0;
function main(){
var button = document.getElementById('button');
if(button.onclick && count == 0){
alert(count);
count = 1;
}
else if(button.onclick && count == 1){
alert(count);
count = 0;
}
}
</script>
</head>
<body>
<button type="button" id="button" onclick="main()">Click Me!</button>
</body>
</html>
You need to hook click event with button and alternate between 0 & 1 on click.
function main() {
var button = document.getElementById('button');
var count = 0;
button.addEventListener("click", function() {
if (count == 0) {
alert(count);
count = 1;
}
else if (count == 1) {
alert(count);
count = 0;
}
});
}
Further make sure that main function is called on when document is in ready state or put function call to main right above closing of body tag. Something like this
<body>
<button type="button" id="button" >Click Me!</button>
<script>
main();
</script>
</body>

Not able to pass variable from one function to another in Javascript

New to Javascript and HTML. In a nutshell, attempting to update score if user enters correct sum of random math problem. Not able to pass the answer of the problem to my function which checks if what the user entered is correct. I just want the score to increase by one. For some reason the function I am passing the parameter "score" to is not being recognized by it.
Here is a very quick example of my code. More concerned about the logic instead of the looks right now of the program. I know right now the score will not update correctly but the problem lies in the passing of the "answer" variable. I will easily work through the score increase once the function at least gets called. Thank you very much for your time!
<html>
<title></title>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body onload = "displayProblem()">
<script>
function displayProblem(){
var answer = (firstNum) + (secondNum);
var firstNum = (Math.floor(Math.random()*10) + 1);
var secondNum = (Math.floor(Math.random()*10) + 1);
document.getElementById("qstns").innerHTML = firstNum +" + " + secondNum +" = ";
}
function checkAnswer(){
var userAnswer = document.getElementById("answr").value;
if(userAnswer === answer){
updateScore();
console.log("score updated");
}
console.log("did not update score");
}
function displayNext(){
document.getElementById("next").style.display = "block";
}
function hideNext(){
document.getElementById("next").style.display = "none";
}
function updateScore(){
var score = 0;
score++;
document.getElementById("score").innerHTML = score;
}
function clearAnswer(){
document.getElementById("answr").value = " ";
}
</script>
<div id="main">
<div id="qstns">
</div>
</div>
<input type="text" id="answr">
Score: <label id="score"> 0 </label>
<button type="Sumbit" id="submit" onclick="displayNext(), checkAnswer ()">Check</button>
<button type="Submit" id="next" onclick="displayProblem(), hideNext(), clearAnswer()" style="display:none;">Next</button>
</body>
</html>
the prob is that every time you call the function "updateScore"
you reset the value of "score" to zero.
one way could be this: read the current score first than increase...
function updateScore(){
var score = pareseInt(document.getElementById("score").innerHTML);
score++;
document.getElementById("score").innerHTML = score;
}
or this: set score to "global" than increase...
var score = 0;
function updateScore(){
score++;
document.getElementById("score").innerHTML = score;
}
Try this:
<html>
<title></title>
<head>
</head>
<body onload="displayProblem()">
<script>
var answer;
var score=0;
function displayProblem(){
var firstNum = (Math.floor(Math.random()*10) + 1);
var secondNum = (Math.floor(Math.random()*10) + 1);
answer = (firstNum) + (secondNum);
document.getElementById("qstns").innerHTML = firstNum +" + " + secondNum +" = ";
}
function checkAnswer(){
var userAnswer = document.getElementById("answr").value;
if(userAnswer == answer)
updateScore();
}
function displayNext(){
document.getElementById("next").style.display = "block";
}
function hideNext(){
document.getElementById("next").style.display = "none";
}
function updateScore(){
score++;
document.getElementById("score").innerHTML = score;
}
function clearAnswer(){
document.getElementById("answr").value = " ";
}
</script>
<div id="main">
<div id="qstns"></div>
</div>
<input type="text" id="answr">Score: <label id="score"> 0 </label></input>
<button type="Sumbit" id="submit" onclick="displayNext(), checkAnswer ()">Check</button>
<button type="Submit" id="next" onclick="displayProblem(), hideNext(), clearAnswer()" style="display:none;">Next</button>
</body>
</html>
You had 2 problems; one that answer was a local variable to displayProblem() and therefore wasn't accessible by checkAnswer(), and two that you were using === instead of ==. === evaluates both type and value, userAnswer and answer are of different types so this was evaluating to false.
JS fiddle
EDIT: score will increment as expected.
<html>
<title></title>
<head>
<link rel='stylesheet' type='text/css' href='style.css'>
</head>
<body onload = 'displayProblem()'>
<script>
//'answer','score' variables should be declared outside function globally
var answer=0;
var score=0;
function displayProblem(){
//var answer = (firstNum) + (secondNum); The calculation should be after assigning value to 'firstNum', 'secondNum'
var firstNum = (Math.floor(Math.random()*10) + 1);
var secondNum = (Math.floor(Math.random()*10) + 1);
answer = (firstNum) + (secondNum);
document.getElementById('qstns').innerHTML = firstNum +' + ' + secondNum +' = ';
}
function checkAnswer(){
var userAnswer = document.getElementById('answr').value;
if(userAnswer == answer){
updateScore();
console.log('score updated');
}
else
console.log('did not update score');
}
function displayNext(){
document.getElementById('next').style.display = 'block';
}
function hideNext(){
document.getElementById('next').style.display = 'none';
}
function updateScore(){
score++;
document.getElementById('score').innerHTML = score;
}
function clearAnswer(){
document.getElementById('answr').value = ' ';
}
</script>
<div id='main'>
<div id='qstns'>
</div>
</div>
<input type='text' id='answr'>
Score: <label id='score'> 0 </label>
<button type='Sumbit' id='submit' onclick='displayNext(), checkAnswer();'>Check</button>
<button type='Submit' id='next' onclick='displayProblem(), hideNext(), clearAnswer();' style='display:none;'>Next</button>
</body>
</html>

Categories