Reputation: 65
Basically I want to have three radio buttons. The first is selected by default. You click the second and it becomes selected. But if you click the second one again, after it is already selected, I would like it to instead re-select the the first. The same behavior for the second one would also apply to the third.
Upvotes: 0
Views: 104
Reputation: 906
here is my solution (no metter how many checkboxes do you use, this code will work):
js:
var curr = '';
var prev = '';
$('input').on('click', function(){
if( curr == $(this).attr('id') ){
if( prev != '' ){
$("#"+prev).prop('checked',true);
prev = '';
}
return;
}
prev = curr;
curr = $(this).attr('id');
});
html:
<input id="rad1" value="1" type="radio" name="rad"/><label for="rad1">Radio 1</label>
<input id="rad2" value="2" type="radio" name="rad"/><label for="rad2">Radio 2</label>
<input id="rad3" value="3" type="radio" name="rad"/><label for="rad3">Radio 3</label>
Upvotes: 1
Reputation: 14287
I have used the radio button onclick
event function logic to arrive at the required functionality:
<p>Select your choice:</p>
<div>
<input type="radio" id="choice1" name="val" value="1" onclick="app(this.value)">
<label for="choice1">First</label>
<input type="radio" id="choice2" name="val" value="2" onclick="app(this.value)">
<label for="choice2">Second</label>
<input type="radio" id="choice3" name="val" value="3" onclick="app(this.value)">
<label for="choice3">Third</label>
</div>
<script src="app.js"></script>
app.js:
var radio2Counter = 0;
var radio3Counter = 0;
function app(selectedVal) {
switch(selectedVal) {
case '2':
radio3Counter = 0;
if (++radio2Counter == 2) {
document.getElementById('choice1').checked = true;
radio2Counter = 0;
}
break;
case '3':
radio2Counter = 0;
if (++radio3Counter == 2) {
document.getElementById('choice1').checked = true;
radio3Counter = 0;
}
break;
default:
// console.log('Radio 1');
}
}
Upvotes: 1
Reputation: 125
use below code to accomplish your requirement.
function CheckDefault()
{
if(this.checked){ document.getElementById('rad1').checked=true;}
}
<input id="rad1" type="radio" name="rad"/><label for="rad1">Radio 1</label>
<input id="rad2" type="radio" name="rad" onclick="CheckDefault()"/><label for="rad2">Radio 2</label>
<input id="rad3" type="radio" name="rad" onclick="CheckDefault()"/><label for="rad3">Radio 3</label>
Upvotes: 0
Reputation: 507
you can select the radio button using css and perform any styles over there
input[type="radio"]:checked+label { font-weight: bold; }
<input id="rad1" type="radio" name="rad"/><label for="rad1">Radio 1</label>
<input id="rad2" type="radio" name="rad"/><label for="rad2">Radio 2</label>
<input id="rad3" type="radio" name="rad"/><label for="rad3">Radio 3</label>
Upvotes: 0