-1

I got this code from another post for making radio buttons look like regular buttons. It works fine but the problem is that the first radio button should be checked, but it is not. Any suggestions, thank you.

<STYLE TYPE="text/css">
.radio-btn-row{display:flex;flex-direction:row;justify-content:center;margin-top: 20px; float:left;}
.radio-btn-wrapper{margin:0px 4px;}
.radio-btn{background-color:#FFFFFF;border:1px solid #666;color:#000;font-size:13px;line-height:26px; width:80px;outline:none;cursor: pointer;}
.radio-btn-selected{background-color:#555;border:1px solid #fff;color:#fff;font-size:13px;line-height:26px; width:80px;outline:none;}
</STYLE >

<div class="radio-btn-row"  style="margin-left: auto;margin-right: 0;">
    <div class="radio-btn-wrapper">
        <button id="UnStitched" name="Stitched" Value="Un-Stitched"  class="radio-btn" type="button" checked="checked" >Un-Stitched</button>
    </div>
    <div class="radio-btn-wrapper">
        <button id="Stitch1" name="Stitched" Value="Stitch1" class="radio-btn" type="button">Stitched</button>
    </div>    
</div>

<script>

$.each($('.radio-btn'), function (key, value) {
        $(this).click(function (e) {
            $('.radio-btn-selected')
                .removeClass('radio-btn-selected')
                .addClass('radio-btn');

            $(this)
                .removeClass('radio-btn')
                .addClass('radio-btn-selected'); 
            });
    });
</script> 

Babar
  • 75
  • 1
  • 7

1 Answers1

0

The problem is with the initialization. After $.each you could add:

$.each($('.radio-btn'), function (key, value) {
        $(this).click(function (e) {
            $('.radio-btn-selected')
                .removeClass('radio-btn-selected')
                .addClass('radio-btn');

            $(this)
                .removeClass('radio-btn')
                .addClass('radio-btn-selected'); 
            });
    });

$('.radio-btn[checked=checked]').removeClass('radio-btn').addClass('radio-btn-selected')
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Dennis4712
  • 16
  • 4
  • Not inside the each statement, but after it in the script. Updated answer – Dennis4712 Sep 05 '21 at 08:12
  • thank you, added https://jsfiddle.net/p9wq36aL/ but it does not seem to work. – Babar Sep 05 '21 at 08:47
  • Had not seen it bas a button and not an actual checkbox. Therefore :checked did not work. Use ` $('.radio-btn[checked=checked]').removeClass('radio-btn').addClass('radio-btn-selected');` instead. – Dennis4712 Sep 05 '21 at 08:54