简体   繁体   中英

Not getting default checked on radio button

I have 10 radio buttons with unique name and these radio buttons are divided into two div. I mean each div have 5 radio buttons and i want to show only one div at a time with first radio button checked. what i want is visible div should have first radio button checked by default. but please note all radio buttons have unique name on a same page.

Below is my code for reference.

<style>
#secondopt, #firstopt { display: none;}
</style>

<script>
function checkme(){
if (document.getElementById("opt1").checked == true){
document.getElementById("firstopt").style.display = "block"
document.getElementById("secondopt").style.display = "none";
}
if (document.getElementById("opt2").checked  == true){
document.getElementById("firstopt").style.display = "none"
document.getElementById("secondopt").style.display = "block";
}
}   
</script>

<form name="form1">
<label><input type="radio" name="opt" id="opt1" onclick="checkme()" /> First opt</label>
<label><input type="radio" name="opt" id="opt2" onclick="checkme()" /> Second Opt</label>
<div id="firstopt">
<label><input type="radio" name="items" value="data1" />Item 1</label>
<label><input type="radio" name="items" value="data2" />Item 2</label>
<label><input type="radio" name="items" value="data3" />Item 3</label>
<label><input type="radio" name="items" value="data4"/>Item 4</label>
<label><input type="radio" name="items" value="data5"/>Item 5</label>
</div>
<div id="secondopt">
<label><input type="radio" name="items" value="data6"/>Item 6</label>
<label><input type="radio" name="items" value="data7"/>Item 7</label>
<label><input type="radio" name="items" value="data8"/>Item 8</label>
<label><input type="radio" name="items" value="data9"/>Item 9</label>
<label><input type="radio" name="items" value="data10"/>Item 10</label>
</div>
</form>

How to achive this?

As you have divided radio buttons in two div, you should also use group property/name of radio buttons. Here give two different groups names and then use selected/checked property using radio button id.

do this



<form name=frmone>
<INPUT TYPE="Radio" Name="payment" Value="CC">Credit Card
<INPUT TYPE="Radio" Name="payment" Value="DC">Debit Card
<INPUT TYPE="Radio" Name="payment" Value="PP">PayPal
</form>
<script>
var len = document.frmOne.payment.length;
for (i = 0; i < len; i++) {

document.frmOne.payment[i].checked ;
break;

}

</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM