Find out if jQuery checks input-radio

Asked 2 years ago, Updated 2 years ago, 36 views

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
    <input type="radio" name="radio12" id="radio1">
    <input type="radio" name="radio12" id="radio2">
    <button type="button" id="btn1">asd</button>

    <script type="text/javascript">

        $('#btn1').on('click',
            function() {
                if($('input[id=radio1]:checked')){
                   window.location.replace('https://www.naver.com/');
                    console.log ("Radio 1");
                }
                else if($('input[id=radio2]:checked')){
                    window.location.replace('https://www.yahoo.com/');
                    console.log ("Radio2");
                }
                else {
                    console.log("recontext");
                }
            }
        );

    </script>
</body>
</html>

If you check the first one and press the button, you will go to Naver. If you press the second one, you will go to Naver. I don't know the solution. ㅠ<

java javascript jquery

2022-09-21 11:17

1 Answers

What you asked: What you want is .is(':checked'). Read Lecture / View demo

if ($('input[id=radio1]').is(':checked')) {
    window.open('https://www.naver.com/');
    console.log ("Radio 1");
}

NOT ASKED: In the context of the code you gave us, $('input[id=radio1]:checked') will be a second query DOM list with length 0. But it doesn't have a length. It doesn't mean it doesn't have a strong presence.So if ($('input[id=radio1]:checked')) is absolutely true. That's why I keep falling into NAVER.


2022-09-21 11:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.