jquery select radio button by value

Posted by w3diy - 4 months ago

JQuery - How to Set Radio Button Checked Based on Value?

<!DOCTYPE html>
<html>
<head>
    <title>jquery set radio button checked based on value - w3diy.com</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h1>jquery set radio button checked based on value - w3diy.com</h1>

<label>
    <input type="radio" name="type" value="1"> User
</label>
<label>
    <input type="radio" name="type" value="2"> Admin
</label>

<button class="btn1">Select User</button>
<button class="btn2">Select Admin</button>

<script>
    $(document).ready(function(){
        $('.btn1').click(function(){
            var value = 1;
            $("input[name=type][value=" + value + "]").prop('checked', true);
        });

        $('.btn2').click(function(){
            var value = 2;
            $("input[name=type][value=" + value + "]").prop('checked', true);
        });
    });
</script>

</body>
</html>