简体   繁体   中英

Radio button show/hide elements in HTML using javascript function

When checkbox is checked it enables the radio buttons. when the first radio button is selected it shows the hidden paragraph, but when the other radio button is selected the paragraph from the first radio button should be hidden( style.display='none' ) and the other paragraph for the second radio button should be shown. https://jsfiddle.net/stevandrej/q3j9a2sj/2/ line 19 - 31

I recommend you that uses jQuery or event listeners by other way. With your code, you iterate by all fields in every click. You can achieve that you want with jquery in few lines. Now, you are only checking one element, if you check radio you listen only that element and is the only that respond.

With jquery:

 $('.checkbox-classname').on('change', function() {
      alert($(this).attr('id')); // alerts you with the id of the checkbox are checked
 });

I introduces some changes :

added one common class to all needed P

HTML -

<p class="radio1 common-class" style="display:none">show me if radio1</p>
<p class="radio2 common-class" style="display:none">show me if radio2</p>

JS -

    var arrP = document.getElementsByClassName("common-class");

    var intLength = arrP.length;

    for(var k=0;k<intLength ;k++){

       arrP[k].style.display = 'none';

    }

Here is the updated Fiddle

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