+ 2
How to use Radio button in html and JavaScript ?
if select Radio button 1 show paragraph number1 if select Radio button 2 show paragraph number2 if select Radio button 3 show paragraph number3 ....... how i do this with html and js help me please. thanks very much â¤
4 Answers
+ 2
https://code.sololearn.com/WvHajWz2cf6D/#html
^Posted the working code here for you. Hope it helps. Let me know if you need me to explain any of it. I've gotten too use to using jQuery, so my JS skills are a bit sloppy, but this should do the trick for you. You should learn jQuery when you get time. ;)
CSS:
.hiddenDiv{
display: none;
}
HTML:
<form>
<input type="radio" id="number1" onclick="javascript:radioCheck(this.id);"
name="paraNum" value="number1"> number1<br>
<input type="radio" id="number2" onclick="javascript:radioCheck(this.id);"
name="paraNum" value="number2"> number2<br>
<input type="radio" id="number3" onclick="javascript:radioCheck(this.id);"
name="paraNum" value="number3"> number3<br>
</form>
<div class="hiddenDiv" id="divNumber1">This is paragraph number 1.</div>
<div class="hiddenDiv" id="divNumber2">This is paragraph number 2.</div>
<div class="hiddenDiv" id="divNumber3">This is paragraph number 3.</div>
JS:
function radioCheck(radioID) {
switch(radioID)
{
case 'number1':
document.getElementById('divNumber1').setAttribute('class', '');
document.getElementById('divNumber2').setAttribute('class', 'hiddenDiv');
document.getElementById('divNumber3').setAttribute('class', 'hiddenDiv');
break;
case 'number2':
document.getElementById('divNumber1').setAttribute('class', 'hiddenDiv');
document.getElementById('divNumber2').setAttribute('class', '');
document.getElementById('divNumber3').setAttribute('class', 'hiddenDiv');
break;
case 'number3':
document.getElementById('divNumber1').setAttribute('class', 'hiddenDiv');
document.getElementById('divNumber2').setAttribute('class', 'hiddenDiv');
document.getElementById('divNumber3').setAttribute('class', '');
break;
}
}
+ 5
Here the code:
<form onclick="update()">
<label><input type="radio" name="para" value="first" /> first</label>
<label><input type="radio" name="para" value="second" /> second</label>
<label><input type="radio" name="para" value="third" /> third</label>
</form>
<p>first paragraph</p>
<p>second paragraph</p>
<p>third paragraph</p>
<script>
form = document.querySelector("form");
p = document.querySelectorAll("p")
update = ()=> form.elements["para"].forEach((r,i)=>p[i].className = r.checked? "show": "");
</script>
https://code.sololearn.com/WR86g5yi4ZB3/?ref=app
+ 4
If you want shorter code.
https://code.sololearn.com/W9iC7tPhZI5m/?ref=app
+ 1
@Legacy: He is using vanilla JavaScript, not jQuery. I recommend using jQuery also but that wasn't his question. :D Calvin has the best response by far.