Reputation: 85
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;
}
Upvotes: 1
Views: 18593
Reputation: 104760
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>
Upvotes: 0
Reputation: 3642
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;
}
Upvotes: 1
Reputation: 823
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++
}
Upvotes: 0
Reputation: 104775
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;
}
Upvotes: 1
Reputation: 22619
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;
}
}
Upvotes: 6